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(Array<Method*>* methods,
1499                                             Symbol* name,
1500                                             Symbol* signature,
1501                                             PrivateLookupMode private_mode) {
1502   Method* meth = InstanceKlass::find_method_impl(methods, name, signature,
1503                                                  find_overpass, skip_static, private_mode);
1504   assert(((meth == NULL) || !meth->is_static()), "find_instance_method should have skipped statics");
1505   return meth;
1506 }
1507 
1508 // find_instance_method looks up the name/signature in the local methods array
1509 // and skips over static methods
1510 Method* InstanceKlass::find_instance_method(Symbol* name,
1511                                             Symbol* signature,
1512                                             PrivateLookupMode private_mode) {
1513   return InstanceKlass::find_instance_method(methods(), name, signature, private_mode);
1514 }
1515 
1516 // Find looks up the name/signature in the local methods array
1517 // and filters on the overpass, static and private flags
1518 // This returns the first one found
1519 // note that the local methods array can have up to one overpass, one static
1520 // and one instance (private or not) with the same name/signature
1521 Method* InstanceKlass::find_local_method(Symbol* name, Symbol* signature,
1522                                         OverpassLookupMode overpass_mode,
1523                                         StaticLookupMode static_mode,
1524                                         PrivateLookupMode private_mode) const {
1525   return InstanceKlass::find_method_impl(methods(), name, signature, overpass_mode, static_mode, private_mode);
1526 }
1527 
1528 // Find looks up the name/signature in the local methods array
1529 // and filters on the overpass, static and private flags
1530 // This returns the first one found
1531 // note that the local methods array can have up to one overpass, one static
1532 // and one instance (private or not) with the same name/signature
1533 Method* InstanceKlass::find_local_method(Array<Method*>* methods,
1534                                         Symbol* name, Symbol* signature,
1535                                         OverpassLookupMode overpass_mode,
1536                                         StaticLookupMode static_mode,
1537                                         PrivateLookupMode private_mode) {
1538   return InstanceKlass::find_method_impl(methods, name, signature, overpass_mode, static_mode, private_mode);
1539 }
1540 
1541 
1542 // find_method looks up the name/signature in the local methods array
1543 Method* InstanceKlass::find_method(
1544     Array<Method*>* methods, Symbol* name, Symbol* signature) {
1545   return InstanceKlass::find_method_impl(methods, name, signature, find_overpass, find_static, find_private);
1546 }
1547 
1548 Method* InstanceKlass::find_method_impl(
1549     Array<Method*>* methods, Symbol* name, Symbol* signature,
1550     OverpassLookupMode overpass_mode, StaticLookupMode static_mode,
1551     PrivateLookupMode private_mode) {
1552   int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode);
1553   return hit >= 0 ? methods->at(hit): NULL;
1554 }
1555 
1556 bool InstanceKlass::method_matches(Method* m, Symbol* signature, bool skipping_overpass, bool skipping_static, bool skipping_private) {
1557     return  ((m->signature() == signature) &&
1558             (!skipping_overpass || !m->is_overpass()) &&
1559             (!skipping_static || !m->is_static()) &&
1560             (!skipping_private || !m->is_private()));
1561 }
1562 
1563 // Used directly for default_methods to find the index into the
1564 // default_vtable_indices, and indirectly by find_method
1565 // find_method_index looks in the local methods array to return the index
1566 // of the matching name/signature. If, overpass methods are being ignored,
1567 // the search continues to find a potential non-overpass match.  This capability
1568 // is important during method resolution to prefer a static method, for example,
1569 // over an overpass method.
1570 // There is the possibility in any _method's array to have the same name/signature
1571 // for a static method, an overpass method and a local instance method
1572 // To correctly catch a given method, the search criteria may need
1573 // to explicitly skip the other two. For local instance methods, it
1574 // is often necessary to skip private methods
1575 int InstanceKlass::find_method_index(
1576     Array<Method*>* methods, Symbol* name, Symbol* signature,
1577     OverpassLookupMode overpass_mode, StaticLookupMode static_mode,
1578     PrivateLookupMode private_mode) {
1579   bool skipping_overpass = (overpass_mode == skip_overpass);
1580   bool skipping_static = (static_mode == skip_static);
1581   bool skipping_private = (private_mode == skip_private);
1582   int hit = binary_search(methods, name);
1583   if (hit != -1) {
1584     Method* m = methods->at(hit);
1585 
1586     // Do linear search to find matching signature.  First, quick check
1587     // for common case, ignoring overpasses if requested.
1588     if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return hit;
1589 
1590     // search downwards through overloaded methods
1591     int i;
1592     for (i = hit - 1; i >= 0; --i) {
1593         Method* m = methods->at(i);
1594         assert(m->is_method(), "must be method");
1595         if (m->name() != name) break;
1596         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return i;
1597     }
1598     // search upwards
1599     for (i = hit + 1; i < methods->length(); ++i) {
1600         Method* m = methods->at(i);
1601         assert(m->is_method(), "must be method");
1602         if (m->name() != name) break;
1603         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return i;
1604     }
1605     // not found
1606 #ifdef ASSERT
1607     int index = (skipping_overpass || skipping_static || skipping_private) ? -1 : linear_search(methods, name, signature);
1608     assert(index == -1, err_msg("binary search should have found entry %d", index));
1609 #endif
1610   }
1611   return -1;
1612 }
1613 int InstanceKlass::find_method_by_name(Symbol* name, int* end) {
1614   return find_method_by_name(methods(), name, end);
1615 }
1616 
1617 int InstanceKlass::find_method_by_name(
1618     Array<Method*>* methods, Symbol* name, int* end_ptr) {
1619   assert(end_ptr != NULL, "just checking");
1620   int start = binary_search(methods, name);
1621   int end = start + 1;
1622   if (start != -1) {
1623     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
1624     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
1625     *end_ptr = end;
1626     return start;
1627   }
1628   return -1;
1629 }
1630 
1631 // uncached_lookup_method searches both the local class methods array and all
1632 // superclasses methods arrays, skipping any overpass methods in superclasses.
1633 Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature, OverpassLookupMode overpass_mode) const {
1634   OverpassLookupMode overpass_local_mode = overpass_mode;
1635   Klass* klass = const_cast<InstanceKlass*>(this);
1636   while (klass != NULL) {
1637     Method* method = InstanceKlass::cast(klass)->find_method_impl(name, signature, overpass_local_mode, find_static, find_private);
1638     if (method != NULL) {
1639       return method;
1640     }
1641     klass = InstanceKlass::cast(klass)->super();
1642     overpass_local_mode = skip_overpass;   // Always ignore overpass methods in superclasses
1643   }
1644   return NULL;
1645 }
1646 
1647 #ifdef ASSERT
1648 // search through class hierarchy and return true if this class or
1649 // one of the superclasses was redefined
1650 bool InstanceKlass::has_redefined_this_or_super() const {
1651   const InstanceKlass* klass = this;
1652   while (klass != NULL) {
1653     if (klass->has_been_redefined()) {
1654       return true;
1655     }
1656     klass = InstanceKlass::cast(klass->super());
1657   }
1658   return false;
1659 }
1660 #endif
1661 
1662 // lookup a method in the default methods list then in all transitive interfaces
1663 // Do NOT return private or static methods
1664 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
1665                                                          Symbol* signature) const {
1666   Method* m = NULL;
1667   if (default_methods() != NULL) {
1668     m = find_method(default_methods(), name, signature);
1669   }
1670   // Look up interfaces
1671   if (m == NULL) {
1672     m = lookup_method_in_all_interfaces(name, signature, find_defaults);
1673   }
1674   return m;
1675 }
1676 
1677 // lookup a method in all the interfaces that this class implements
1678 // Do NOT return private or static methods, new in JDK8 which are not externally visible
1679 // They should only be found in the initial InterfaceMethodRef
1680 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
1681                                                        Symbol* signature,
1682                                                        DefaultsLookupMode defaults_mode) const {
1683   Array<Klass*>* all_ifs = transitive_interfaces();
1684   int num_ifs = all_ifs->length();
1685   InstanceKlass *ik = NULL;
1686   for (int i = 0; i < num_ifs; i++) {
1687     ik = InstanceKlass::cast(all_ifs->at(i));
1688     Method* m = ik->lookup_method(name, signature);
1689     if (m != NULL && m->is_public() && !m->is_static() &&
1690         ((defaults_mode != skip_defaults) || !m->is_default_method())) {
1691       return m;
1692     }
1693   }
1694   return NULL;
1695 }
1696 
1697 /* jni_id_for_impl for jfieldIds only */
1698 JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_oop, int offset) {
1699   MutexLocker ml(JfieldIdCreation_lock);
1700   // Retry lookup after we got the lock
1701   JNIid* probe = this_oop->jni_ids() == NULL ? NULL : this_oop->jni_ids()->find(offset);
1702   if (probe == NULL) {
1703     // Slow case, allocate new static field identifier
1704     probe = new JNIid(this_oop(), offset, this_oop->jni_ids());
1705     this_oop->set_jni_ids(probe);
1706   }
1707   return probe;
1708 }
1709 
1710 
1711 /* jni_id_for for jfieldIds only */
1712 JNIid* InstanceKlass::jni_id_for(int offset) {
1713   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
1714   if (probe == NULL) {
1715     probe = jni_id_for_impl(this, offset);
1716   }
1717   return probe;
1718 }
1719 
1720 u2 InstanceKlass::enclosing_method_data(int offset) {
1721   Array<jushort>* inner_class_list = inner_classes();
1722   if (inner_class_list == NULL) {
1723     return 0;
1724   }
1725   int length = inner_class_list->length();
1726   if (length % inner_class_next_offset == 0) {
1727     return 0;
1728   } else {
1729     int index = length - enclosing_method_attribute_size;
1730     assert(offset < enclosing_method_attribute_size, "invalid offset");
1731     return inner_class_list->at(index + offset);
1732   }
1733 }
1734 
1735 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
1736                                                  u2 method_index) {
1737   Array<jushort>* inner_class_list = inner_classes();
1738   assert (inner_class_list != NULL, "_inner_classes list is not set up");
1739   int length = inner_class_list->length();
1740   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
1741     int index = length - enclosing_method_attribute_size;
1742     inner_class_list->at_put(
1743       index + enclosing_method_class_index_offset, class_index);
1744     inner_class_list->at_put(
1745       index + enclosing_method_method_index_offset, method_index);
1746   }
1747 }
1748 
1749 // Lookup or create a jmethodID.
1750 // This code is called by the VMThread and JavaThreads so the
1751 // locking has to be done very carefully to avoid deadlocks
1752 // and/or other cache consistency problems.
1753 //
1754 jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {
1755   size_t idnum = (size_t)method_h->method_idnum();
1756   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
1757   size_t length = 0;
1758   jmethodID id = NULL;
1759 
1760   // We use a double-check locking idiom here because this cache is
1761   // performance sensitive. In the normal system, this cache only
1762   // transitions from NULL to non-NULL which is safe because we use
1763   // release_set_methods_jmethod_ids() to advertise the new cache.
1764   // A partially constructed cache should never be seen by a racing
1765   // thread. We also use release_store_ptr() to save a new jmethodID
1766   // in the cache so a partially constructed jmethodID should never be
1767   // seen either. Cache reads of existing jmethodIDs proceed without a
1768   // lock, but cache writes of a new jmethodID requires uniqueness and
1769   // creation of the cache itself requires no leaks so a lock is
1770   // generally acquired in those two cases.
1771   //
1772   // If the RedefineClasses() API has been used, then this cache can
1773   // grow and we'll have transitions from non-NULL to bigger non-NULL.
1774   // Cache creation requires no leaks and we require safety between all
1775   // cache accesses and freeing of the old cache so a lock is generally
1776   // acquired when the RedefineClasses() API has been used.
1777 
1778   if (jmeths != NULL) {
1779     // the cache already exists
1780     if (!ik_h->idnum_can_increment()) {
1781       // the cache can't grow so we can just get the current values
1782       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1783     } else {
1784       // cache can grow so we have to be more careful
1785       if (Threads::number_of_threads() == 0 ||
1786           SafepointSynchronize::is_at_safepoint()) {
1787         // we're single threaded or at a safepoint - no locking needed
1788         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1789       } else {
1790         MutexLocker ml(JmethodIdCreation_lock);
1791         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1792       }
1793     }
1794   }
1795   // implied else:
1796   // we need to allocate a cache so default length and id values are good
1797 
1798   if (jmeths == NULL ||   // no cache yet
1799       length <= idnum ||  // cache is too short
1800       id == NULL) {       // cache doesn't contain entry
1801 
1802     // This function can be called by the VMThread so we have to do all
1803     // things that might block on a safepoint before grabbing the lock.
1804     // Otherwise, we can deadlock with the VMThread or have a cache
1805     // consistency issue. These vars keep track of what we might have
1806     // to free after the lock is dropped.
1807     jmethodID  to_dealloc_id     = NULL;
1808     jmethodID* to_dealloc_jmeths = NULL;
1809 
1810     // may not allocate new_jmeths or use it if we allocate it
1811     jmethodID* new_jmeths = NULL;
1812     if (length <= idnum) {
1813       // allocate a new cache that might be used
1814       size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
1815       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
1816       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
1817       // cache size is stored in element[0], other elements offset by one
1818       new_jmeths[0] = (jmethodID)size;
1819     }
1820 
1821     // allocate a new jmethodID that might be used
1822     jmethodID new_id = NULL;
1823     if (method_h->is_old() && !method_h->is_obsolete()) {
1824       // The method passed in is old (but not obsolete), we need to use the current version
1825       Method* current_method = ik_h->method_with_idnum((int)idnum);
1826       assert(current_method != NULL, "old and but not obsolete, so should exist");
1827       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);
1828     } else {
1829       // It is the current version of the method or an obsolete method,
1830       // use the version passed in
1831       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());
1832     }
1833 
1834     if (Threads::number_of_threads() == 0 ||
1835         SafepointSynchronize::is_at_safepoint()) {
1836       // we're single threaded or at a safepoint - no locking needed
1837       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
1838                                           &to_dealloc_id, &to_dealloc_jmeths);
1839     } else {
1840       MutexLocker ml(JmethodIdCreation_lock);
1841       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
1842                                           &to_dealloc_id, &to_dealloc_jmeths);
1843     }
1844 
1845     // The lock has been dropped so we can free resources.
1846     // Free up either the old cache or the new cache if we allocated one.
1847     if (to_dealloc_jmeths != NULL) {
1848       FreeHeap(to_dealloc_jmeths);
1849     }
1850     // free up the new ID since it wasn't needed
1851     if (to_dealloc_id != NULL) {
1852       Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);
1853     }
1854   }
1855   return id;
1856 }
1857 
1858 
1859 // Common code to fetch the jmethodID from the cache or update the
1860 // cache with the new jmethodID. This function should never do anything
1861 // that causes the caller to go to a safepoint or we can deadlock with
1862 // the VMThread or have cache consistency issues.
1863 //
1864 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
1865             instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,
1866             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
1867             jmethodID** to_dealloc_jmeths_p) {
1868   assert(new_id != NULL, "sanity check");
1869   assert(to_dealloc_id_p != NULL, "sanity check");
1870   assert(to_dealloc_jmeths_p != NULL, "sanity check");
1871   assert(Threads::number_of_threads() == 0 ||
1872          SafepointSynchronize::is_at_safepoint() ||
1873          JmethodIdCreation_lock->owned_by_self(), "sanity check");
1874 
1875   // reacquire the cache - we are locked, single threaded or at a safepoint
1876   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
1877   jmethodID  id     = NULL;
1878   size_t     length = 0;
1879 
1880   if (jmeths == NULL ||                         // no cache yet
1881       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
1882     if (jmeths != NULL) {
1883       // copy any existing entries from the old cache
1884       for (size_t index = 0; index < length; index++) {
1885         new_jmeths[index+1] = jmeths[index+1];
1886       }
1887       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
1888     }
1889     ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
1890   } else {
1891     // fetch jmethodID (if any) from the existing cache
1892     id = jmeths[idnum+1];
1893     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
1894   }
1895   if (id == NULL) {
1896     // No matching jmethodID in the existing cache or we have a new
1897     // cache or we just grew the cache. This cache write is done here
1898     // by the first thread to win the foot race because a jmethodID
1899     // needs to be unique once it is generally available.
1900     id = new_id;
1901 
1902     // The jmethodID cache can be read while unlocked so we have to
1903     // make sure the new jmethodID is complete before installing it
1904     // in the cache.
1905     OrderAccess::release_store_ptr(&jmeths[idnum+1], id);
1906   } else {
1907     *to_dealloc_id_p = new_id; // save new id for later delete
1908   }
1909   return id;
1910 }
1911 
1912 
1913 // Common code to get the jmethodID cache length and the jmethodID
1914 // value at index idnum if there is one.
1915 //
1916 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
1917        size_t idnum, size_t *length_p, jmethodID* id_p) {
1918   assert(cache != NULL, "sanity check");
1919   assert(length_p != NULL, "sanity check");
1920   assert(id_p != NULL, "sanity check");
1921 
1922   // cache size is stored in element[0], other elements offset by one
1923   *length_p = (size_t)cache[0];
1924   if (*length_p <= idnum) {  // cache is too short
1925     *id_p = NULL;
1926   } else {
1927     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
1928   }
1929 }
1930 
1931 
1932 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
1933 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
1934   size_t idnum = (size_t)method->method_idnum();
1935   jmethodID* jmeths = methods_jmethod_ids_acquire();
1936   size_t length;                                // length assigned as debugging crumb
1937   jmethodID id = NULL;
1938   if (jmeths != NULL &&                         // If there is a cache
1939       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
1940     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
1941   }
1942   return id;
1943 }
1944 
1945 int nmethodBucket::decrement() {
1946   return Atomic::add(-1, (volatile int *)&_count);
1947 }
1948 
1949 //
1950 // Walk the list of dependent nmethods searching for nmethods which
1951 // are dependent on the changes that were passed in and mark them for
1952 // deoptimization.  Returns the number of nmethods found.
1953 //
1954 int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {
1955   assert_locked_or_safepoint(CodeCache_lock);
1956   int found = 0;
1957   nmethodBucket* b = _dependencies;
1958   while (b != NULL) {
1959     nmethod* nm = b->get_nmethod();
1960     // since dependencies aren't removed until an nmethod becomes a zombie,
1961     // the dependency list may contain nmethods which aren't alive.
1962     if (b->count() > 0 && nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
1963       if (TraceDependencies) {
1964         ResourceMark rm;
1965         tty->print_cr("Marked for deoptimization");
1966         tty->print_cr("  context = %s", this->external_name());
1967         changes.print();
1968         nm->print();
1969         nm->print_dependencies();
1970       }
1971       nm->mark_for_deoptimization();
1972       found++;
1973     }
1974     b = b->next();
1975   }
1976   return found;
1977 }
1978 
1979 void InstanceKlass::clean_dependent_nmethods() {
1980   assert_locked_or_safepoint(CodeCache_lock);
1981 
1982   if (has_unloaded_dependent()) {
1983     nmethodBucket* b = _dependencies;
1984     nmethodBucket* last = NULL;
1985     while (b != NULL) {
1986       assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));
1987 
1988       nmethodBucket* next = b->next();
1989 
1990       if (b->count() == 0) {
1991         if (last == NULL) {
1992           _dependencies = next;
1993         } else {
1994           last->set_next(next);
1995         }
1996         delete b;
1997         // last stays the same.
1998       } else {
1999         last = b;
2000       }
2001 
2002       b = next;
2003     }
2004     set_has_unloaded_dependent(false);
2005   }
2006 #ifdef ASSERT
2007   else {
2008     // Verification
2009     for (nmethodBucket* b = _dependencies; b != NULL; b = b->next()) {
2010       assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));
2011       assert(b->count() != 0, "empty buckets need to be cleaned");
2012     }
2013   }
2014 #endif
2015 }
2016 
2017 //
2018 // Add an nmethodBucket to the list of dependencies for this nmethod.
2019 // It's possible that an nmethod has multiple dependencies on this klass
2020 // so a count is kept for each bucket to guarantee that creation and
2021 // deletion of dependencies is consistent.
2022 //
2023 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2024   assert_locked_or_safepoint(CodeCache_lock);
2025   nmethodBucket* b = _dependencies;
2026   nmethodBucket* last = NULL;
2027   while (b != NULL) {
2028     if (nm == b->get_nmethod()) {
2029       b->increment();
2030       return;
2031     }
2032     b = b->next();
2033   }
2034   _dependencies = new nmethodBucket(nm, _dependencies);
2035 }
2036 
2037 
2038 //
2039 // Decrement count of the nmethod in the dependency list and remove
2040 // the bucket competely when the count goes to 0.  This method must
2041 // find a corresponding bucket otherwise there's a bug in the
2042 // recording of dependecies.
2043 //
2044 void InstanceKlass::remove_dependent_nmethod(nmethod* nm, bool delete_immediately) {
2045   assert_locked_or_safepoint(CodeCache_lock);
2046   nmethodBucket* b = _dependencies;
2047   nmethodBucket* last = NULL;
2048   while (b != NULL) {
2049     if (nm == b->get_nmethod()) {
2050       int val = b->decrement();
2051       guarantee(val >= 0, err_msg("Underflow: %d", val));
2052       if (val == 0) {
2053         if (delete_immediately) {
2054           if (last == NULL) {
2055             _dependencies = b->next();
2056           } else {
2057             last->set_next(b->next());
2058           }
2059           delete b;
2060         } else {
2061           // The deletion of this entry is deferred until a later, potentially parallel GC phase.
2062           set_has_unloaded_dependent(true);
2063         }
2064       }
2065       return;
2066     }
2067     last = b;
2068     b = b->next();
2069   }
2070 #ifdef ASSERT
2071   tty->print_cr("### %s can't find dependent nmethod:", this->external_name());
2072   nm->print();
2073 #endif // ASSERT
2074   ShouldNotReachHere();
2075 }
2076 
2077 
2078 #ifndef PRODUCT
2079 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2080   nmethodBucket* b = _dependencies;
2081   int idx = 0;
2082   while (b != NULL) {
2083     nmethod* nm = b->get_nmethod();
2084     tty->print("[%d] count=%d { ", idx++, b->count());
2085     if (!verbose) {
2086       nm->print_on(tty, "nmethod");
2087       tty->print_cr(" } ");
2088     } else {
2089       nm->print();
2090       nm->print_dependencies();
2091       tty->print_cr("--- } ");
2092     }
2093     b = b->next();
2094   }
2095 }
2096 
2097 
2098 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2099   nmethodBucket* b = _dependencies;
2100   while (b != NULL) {
2101     if (nm == b->get_nmethod()) {
2102 #ifdef ASSERT
2103       int count = b->count();
2104       assert(count >= 0, err_msg("count shouldn't be negative: %d", count));
2105 #endif
2106       return true;
2107     }
2108     b = b->next();
2109   }
2110   return false;
2111 }
2112 #endif //PRODUCT
2113 
2114 
2115 // Garbage collection
2116 
2117 #ifdef ASSERT
2118 template <class T> void assert_is_in(T *p) {
2119   T heap_oop = oopDesc::load_heap_oop(p);
2120   if (!oopDesc::is_null(heap_oop)) {
2121     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
2122     assert(Universe::heap()->is_in(o), "should be in heap");
2123   }
2124 }
2125 template <class T> void assert_is_in_closed_subset(T *p) {
2126   T heap_oop = oopDesc::load_heap_oop(p);
2127   if (!oopDesc::is_null(heap_oop)) {
2128     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
2129     assert(Universe::heap()->is_in_closed_subset(o),
2130            err_msg("should be in closed *p " INTPTR_FORMAT " " INTPTR_FORMAT, (address)p, (address)o));
2131   }
2132 }
2133 template <class T> void assert_is_in_reserved(T *p) {
2134   T heap_oop = oopDesc::load_heap_oop(p);
2135   if (!oopDesc::is_null(heap_oop)) {
2136     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
2137     assert(Universe::heap()->is_in_reserved(o), "should be in reserved");
2138   }
2139 }
2140 template <class T> void assert_nothing(T *p) {}
2141 
2142 #else
2143 template <class T> void assert_is_in(T *p) {}
2144 template <class T> void assert_is_in_closed_subset(T *p) {}
2145 template <class T> void assert_is_in_reserved(T *p) {}
2146 template <class T> void assert_nothing(T *p) {}
2147 #endif // ASSERT
2148 
2149 //
2150 // Macros that iterate over areas of oops which are specialized on type of
2151 // oop pointer either narrow or wide, depending on UseCompressedOops
2152 //
2153 // Parameters are:
2154 //   T         - type of oop to point to (either oop or narrowOop)
2155 //   start_p   - starting pointer for region to iterate over
2156 //   count     - number of oops or narrowOops to iterate over
2157 //   do_oop    - action to perform on each oop (it's arbitrary C code which
2158 //               makes it more efficient to put in a macro rather than making
2159 //               it a template function)
2160 //   assert_fn - assert function which is template function because performance
2161 //               doesn't matter when enabled.
2162 #define InstanceKlass_SPECIALIZED_OOP_ITERATE( \
2163   T, start_p, count, do_oop,                \
2164   assert_fn)                                \
2165 {                                           \
2166   T* p         = (T*)(start_p);             \
2167   T* const end = p + (count);               \
2168   while (p < end) {                         \
2169     (assert_fn)(p);                         \
2170     do_oop;                                 \
2171     ++p;                                    \
2172   }                                         \
2173 }
2174 
2175 #define InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE( \
2176   T, start_p, count, do_oop,                \
2177   assert_fn)                                \
2178 {                                           \
2179   T* const start = (T*)(start_p);           \
2180   T*       p     = start + (count);         \
2181   while (start < p) {                       \
2182     --p;                                    \
2183     (assert_fn)(p);                         \
2184     do_oop;                                 \
2185   }                                         \
2186 }
2187 
2188 #define InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE( \
2189   T, start_p, count, low, high,             \
2190   do_oop, assert_fn)                        \
2191 {                                           \
2192   T* const l = (T*)(low);                   \
2193   T* const h = (T*)(high);                  \
2194   assert(mask_bits((intptr_t)l, sizeof(T)-1) == 0 && \
2195          mask_bits((intptr_t)h, sizeof(T)-1) == 0,   \
2196          "bounded region must be properly aligned"); \
2197   T* p       = (T*)(start_p);               \
2198   T* end     = p + (count);                 \
2199   if (p < l) p = l;                         \
2200   if (end > h) end = h;                     \
2201   while (p < end) {                         \
2202     (assert_fn)(p);                         \
2203     do_oop;                                 \
2204     ++p;                                    \
2205   }                                         \
2206 }
2207 
2208 
2209 // The following macros call specialized macros, passing either oop or
2210 // narrowOop as the specialization type.  These test the UseCompressedOops
2211 // flag.
2212 #define InstanceKlass_OOP_MAP_ITERATE(obj, do_oop, assert_fn)            \
2213 {                                                                        \
2214   /* Compute oopmap block range. The common case                         \
2215      is nonstatic_oop_map_size == 1. */                                  \
2216   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
2217   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
2218   if (UseCompressedOops) {                                               \
2219     while (map < end_map) {                                              \
2220       InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop,                   \
2221         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
2222         do_oop, assert_fn)                                               \
2223       ++map;                                                             \
2224     }                                                                    \
2225   } else {                                                               \
2226     while (map < end_map) {                                              \
2227       InstanceKlass_SPECIALIZED_OOP_ITERATE(oop,                         \
2228         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
2229         do_oop, assert_fn)                                               \
2230       ++map;                                                             \
2231     }                                                                    \
2232   }                                                                      \
2233 }
2234 
2235 #define InstanceKlass_OOP_MAP_REVERSE_ITERATE(obj, do_oop, assert_fn)    \
2236 {                                                                        \
2237   OopMapBlock* const start_map = start_of_nonstatic_oop_maps();          \
2238   OopMapBlock* map             = start_map + nonstatic_oop_map_count();  \
2239   if (UseCompressedOops) {                                               \
2240     while (start_map < map) {                                            \
2241       --map;                                                             \
2242       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop,           \
2243         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
2244         do_oop, assert_fn)                                               \
2245     }                                                                    \
2246   } else {                                                               \
2247     while (start_map < map) {                                            \
2248       --map;                                                             \
2249       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop,                 \
2250         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
2251         do_oop, assert_fn)                                               \
2252     }                                                                    \
2253   }                                                                      \
2254 }
2255 
2256 #define InstanceKlass_BOUNDED_OOP_MAP_ITERATE(obj, low, high, do_oop,    \
2257                                               assert_fn)                 \
2258 {                                                                        \
2259   /* Compute oopmap block range. The common case is                      \
2260      nonstatic_oop_map_size == 1, so we accept the                       \
2261      usually non-existent extra overhead of examining                    \
2262      all the maps. */                                                    \
2263   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
2264   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
2265   if (UseCompressedOops) {                                               \
2266     while (map < end_map) {                                              \
2267       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop,           \
2268         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
2269         low, high,                                                       \
2270         do_oop, assert_fn)                                               \
2271       ++map;                                                             \
2272     }                                                                    \
2273   } else {                                                               \
2274     while (map < end_map) {                                              \
2275       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop,                 \
2276         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
2277         low, high,                                                       \
2278         do_oop, assert_fn)                                               \
2279       ++map;                                                             \
2280     }                                                                    \
2281   }                                                                      \
2282 }
2283 
2284 void InstanceKlass::oop_follow_contents(oop obj) {
2285   assert(obj != NULL, "can't follow the content of NULL object");
2286   MarkSweep::follow_klass(obj->klass());
2287   InstanceKlass_OOP_MAP_ITERATE( \
2288     obj, \
2289     MarkSweep::mark_and_push(p), \
2290     assert_is_in_closed_subset)
2291 }
2292 
2293 #if INCLUDE_ALL_GCS
2294 void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,
2295                                         oop obj) {
2296   assert(obj != NULL, "can't follow the content of NULL object");
2297   PSParallelCompact::follow_klass(cm, obj->klass());
2298   // Only mark the header and let the scan of the meta-data mark
2299   // everything else.
2300   InstanceKlass_OOP_MAP_ITERATE( \
2301     obj, \
2302     PSParallelCompact::mark_and_push(cm, p), \
2303     assert_is_in)
2304 }
2305 #endif // INCLUDE_ALL_GCS
2306 
2307 // closure's do_metadata() method dictates whether the given closure should be
2308 // applied to the klass ptr in the object header.
2309 
2310 #define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)        \
2311                                                                              \
2312 int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \
2313   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
2314   /* header */                                                          \
2315   if_do_metadata_checked(closure, nv_suffix) {                          \
2316     closure->do_klass##nv_suffix(obj->klass());                         \
2317   }                                                                     \
2318   InstanceKlass_OOP_MAP_ITERATE(                                        \
2319     obj,                                                                \
2320     SpecializationStats::                                               \
2321       record_do_oop_call##nv_suffix(SpecializationStats::ik);           \
2322     (closure)->do_oop##nv_suffix(p),                                    \
2323     assert_is_in_closed_subset)                                         \
2324   return size_helper();                                                 \
2325 }
2326 
2327 #if INCLUDE_ALL_GCS
2328 #define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
2329                                                                                 \
2330 int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj,                \
2331                                               OopClosureType* closure) {        \
2332   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \
2333                                                                                 \
2334   assert_should_ignore_metadata(closure, nv_suffix);                            \
2335                                                                                 \
2336   /* instance variables */                                                      \
2337   InstanceKlass_OOP_MAP_REVERSE_ITERATE(                                        \
2338     obj,                                                                        \
2339     SpecializationStats::record_do_oop_call##nv_suffix(SpecializationStats::ik);\
2340     (closure)->do_oop##nv_suffix(p),                                            \
2341     assert_is_in_closed_subset)                                                 \
2342    return size_helper();                                                        \
2343 }
2344 #endif // INCLUDE_ALL_GCS
2345 
2346 #define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \
2347                                                                         \
2348 int InstanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj,              \
2349                                                   OopClosureType* closure, \
2350                                                   MemRegion mr) {          \
2351   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
2352   if_do_metadata_checked(closure, nv_suffix) {                           \
2353     if (mr.contains(obj)) {                                              \
2354       closure->do_klass##nv_suffix(obj->klass());                        \
2355     }                                                                    \
2356   }                                                                      \
2357   InstanceKlass_BOUNDED_OOP_MAP_ITERATE(                                 \
2358     obj, mr.start(), mr.end(),                                           \
2359     (closure)->do_oop##nv_suffix(p),                                     \
2360     assert_is_in_closed_subset)                                          \
2361   return size_helper();                                                  \
2362 }
2363 
2364 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)
2365 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)
2366 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
2367 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
2368 #if INCLUDE_ALL_GCS
2369 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
2370 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
2371 #endif // INCLUDE_ALL_GCS
2372 
2373 int InstanceKlass::oop_adjust_pointers(oop obj) {
2374   int size = size_helper();
2375   InstanceKlass_OOP_MAP_ITERATE( \
2376     obj, \
2377     MarkSweep::adjust_pointer(p), \
2378     assert_is_in)
2379   return size;
2380 }
2381 
2382 #if INCLUDE_ALL_GCS
2383 void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
2384   InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
2385     obj, \
2386     if (PSScavenge::should_scavenge(p)) { \
2387       pm->claim_or_forward_depth(p); \
2388     }, \
2389     assert_nothing )
2390 }
2391 
2392 int InstanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {
2393   int size = size_helper();
2394   InstanceKlass_OOP_MAP_ITERATE( \
2395     obj, \
2396     PSParallelCompact::adjust_pointer(p), \
2397     assert_is_in)
2398   return size;
2399 }
2400 
2401 #endif // INCLUDE_ALL_GCS
2402 
2403 void InstanceKlass::clean_weak_instanceklass_links(BoolObjectClosure* is_alive) {
2404   clean_implementors_list(is_alive);
2405   clean_method_data(is_alive);
2406 
2407   clean_dependent_nmethods();
2408 }
2409 
2410 void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
2411   assert(class_loader_data()->is_alive(is_alive), "this klass should be live");
2412   if (is_interface()) {
2413     if (ClassUnloading) {
2414       Klass* impl = implementor();
2415       if (impl != NULL) {
2416         if (!impl->is_loader_alive(is_alive)) {
2417           // remove this guy
2418           Klass** klass = adr_implementor();
2419           assert(klass != NULL, "null klass");
2420           if (klass != NULL) {
2421             *klass = NULL;
2422           }
2423         }
2424       }
2425     }
2426   }
2427 }
2428 
2429 void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {
2430   for (int m = 0; m < methods()->length(); m++) {
2431     MethodData* mdo = methods()->at(m)->method_data();
2432     if (mdo != NULL) {
2433       mdo->clean_method_data(is_alive);
2434     }
2435   }
2436 }
2437 
2438 
2439 static void remove_unshareable_in_class(Klass* k) {
2440   // remove klass's unshareable info
2441   k->remove_unshareable_info();
2442 }
2443 
2444 void InstanceKlass::remove_unshareable_info() {
2445   Klass::remove_unshareable_info();
2446   // Unlink the class
2447   if (is_linked()) {
2448     unlink_class();
2449   }
2450   init_implementor();
2451 
2452   constants()->remove_unshareable_info();
2453 
2454   for (int i = 0; i < methods()->length(); i++) {
2455     Method* m = methods()->at(i);
2456     m->remove_unshareable_info();
2457   }
2458 
2459   // do array classes also.
2460   array_klasses_do(remove_unshareable_in_class);
2461 }
2462 
2463 static void restore_unshareable_in_class(Klass* k, TRAPS) {
2464   // Array classes have null protection domain.
2465   // --> see ArrayKlass::complete_create_array_klass()
2466   k->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);
2467 }
2468 
2469 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
2470   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2471   instanceKlassHandle ik(THREAD, this);
2472 
2473   Array<Method*>* methods = ik->methods();
2474   int num_methods = methods->length();
2475   for (int index2 = 0; index2 < num_methods; ++index2) {
2476     methodHandle m(THREAD, methods->at(index2));
2477     m->restore_unshareable_info(CHECK);
2478   }
2479   if (JvmtiExport::has_redefined_a_class()) {
2480     // Reinitialize vtable because RedefineClasses may have changed some
2481     // entries in this vtable for super classes so the CDS vtable might
2482     // point to old or obsolete entries.  RedefineClasses doesn't fix up
2483     // vtables in the shared system dictionary, only the main one.
2484     // It also redefines the itable too so fix that too.
2485     ResourceMark rm(THREAD);
2486     ik->vtable()->initialize_vtable(false, CHECK);
2487     ik->itable()->initialize_itable(false, CHECK);
2488   }
2489 
2490   // restore constant pool resolved references
2491   ik->constants()->restore_unshareable_info(CHECK);
2492 
2493   ik->array_klasses_do(restore_unshareable_in_class, CHECK);
2494 }
2495 
2496 // returns true IFF is_in_error_state() has been changed as a result of this call.
2497 bool InstanceKlass::check_sharing_error_state() {
2498   assert(DumpSharedSpaces, "should only be called during dumping");
2499   bool old_state = is_in_error_state();
2500 
2501   if (!is_in_error_state()) {
2502     bool bad = false;
2503     for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) {
2504       if (sup->is_in_error_state()) {
2505         bad = true;
2506         break;
2507       }
2508     }
2509     if (!bad) {
2510       Array<Klass*>* interfaces = transitive_interfaces();
2511       for (int i = 0; i < interfaces->length(); i++) {
2512         Klass* iface = interfaces->at(i);
2513         if (InstanceKlass::cast(iface)->is_in_error_state()) {
2514           bad = true;
2515           break;
2516         }
2517       }
2518     }
2519 
2520     if (bad) {
2521       set_in_error_state();
2522     }
2523   }
2524 
2525   return (old_state != is_in_error_state());
2526 }
2527 
2528 static void clear_all_breakpoints(Method* m) {
2529   m->clear_all_breakpoints();
2530 }
2531 
2532 
2533 void InstanceKlass::notify_unload_class(InstanceKlass* ik) {
2534   // notify the debugger
2535   if (JvmtiExport::should_post_class_unload()) {
2536     JvmtiExport::post_class_unload(ik);
2537   }
2538 
2539   // notify ClassLoadingService of class unload
2540   ClassLoadingService::notify_class_unloaded(ik);
2541 
2542 #if INCLUDE_JFR
2543   assert(ik != NULL, "invariant");
2544   EventClassUnload event;
2545   event.set_unloadedClass(ik);
2546   event.set_definingClassLoader(ik->class_loader_data());
2547   event.commit();
2548 #endif
2549 }
2550 
2551 void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {
2552   // Clean up C heap
2553   ik->release_C_heap_structures();
2554   ik->constants()->release_C_heap_structures();
2555 }
2556 
2557 void InstanceKlass::release_C_heap_structures() {
2558 
2559   // Can't release the constant pool here because the constant pool can be
2560   // deallocated separately from the InstanceKlass for default methods and
2561   // redefine classes.
2562 
2563   // Deallocate oop map cache
2564   if (_oop_map_cache != NULL) {
2565     delete _oop_map_cache;
2566     _oop_map_cache = NULL;
2567   }
2568 
2569   // Deallocate JNI identifiers for jfieldIDs
2570   JNIid::deallocate(jni_ids());
2571   set_jni_ids(NULL);
2572 
2573   jmethodID* jmeths = methods_jmethod_ids_acquire();
2574   if (jmeths != (jmethodID*)NULL) {
2575     release_set_methods_jmethod_ids(NULL);
2576     FreeHeap(jmeths);
2577   }
2578 
2579   // Deallocate MemberNameTable
2580   {
2581     Mutex* lock_or_null = SafepointSynchronize::is_at_safepoint() ? NULL : MemberNameTable_lock;
2582     MutexLockerEx ml(lock_or_null, Mutex::_no_safepoint_check_flag);
2583     MemberNameTable* mnt = member_names();
2584     if (mnt != NULL) {
2585       delete mnt;
2586       set_member_names(NULL);
2587     }
2588   }
2589 
2590   // release dependencies
2591   nmethodBucket* b = _dependencies;
2592   _dependencies = NULL;
2593   while (b != NULL) {
2594     nmethodBucket* next = b->next();
2595     delete b;
2596     b = next;
2597   }
2598 
2599   // Deallocate breakpoint records
2600   if (breakpoints() != 0x0) {
2601     methods_do(clear_all_breakpoints);
2602     assert(breakpoints() == 0x0, "should have cleared breakpoints");
2603   }
2604 
2605   // deallocate the cached class file
2606   if (_cached_class_file != NULL) {
2607     os::free(_cached_class_file, mtClass);
2608     _cached_class_file = NULL;
2609   }
2610 
2611   // Decrement symbol reference counts associated with the unloaded class.
2612   if (_name != NULL) _name->decrement_refcount();
2613   // unreference array name derived from this class name (arrays of an unloaded
2614   // class can't be referenced anymore).
2615   if (_array_name != NULL)  _array_name->decrement_refcount();
2616   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);
2617 
2618   assert(_total_instanceKlass_count >= 1, "Sanity check");
2619   Atomic::dec(&_total_instanceKlass_count);
2620 }
2621 
2622 void InstanceKlass::set_source_debug_extension(char* array, int length) {
2623   if (array == NULL) {
2624     _source_debug_extension = NULL;
2625   } else {
2626     // Adding one to the attribute length in order to store a null terminator
2627     // character could cause an overflow because the attribute length is
2628     // already coded with an u4 in the classfile, but in practice, it's
2629     // unlikely to happen.
2630     assert((length+1) > length, "Overflow checking");
2631     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2632     for (int i = 0; i < length; i++) {
2633       sde[i] = array[i];
2634     }
2635     sde[length] = '\0';
2636     _source_debug_extension = sde;
2637   }
2638 }
2639 
2640 address InstanceKlass::static_field_addr(int offset) {
2641   return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror()));
2642 }
2643 
2644 
2645 const char* InstanceKlass::signature_name() const {
2646   int hash_len = 0;
2647   char hash_buf[40];
2648 
2649   // If this is an anonymous class, append a hash to make the name unique
2650   if (is_anonymous()) {
2651     assert(EnableInvokeDynamic, "EnableInvokeDynamic was not set.");
2652     intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
2653     sprintf(hash_buf, "/" UINTX_FORMAT, (uintx)hash);
2654     hash_len = (int)strlen(hash_buf);
2655   }
2656 
2657   // Get the internal name as a c string
2658   const char* src = (const char*) (name()->as_C_string());
2659   const int src_length = (int)strlen(src);
2660 
2661   char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
2662 
2663   // Add L as type indicator
2664   int dest_index = 0;
2665   dest[dest_index++] = 'L';
2666 
2667   // Add the actual class name
2668   for (int src_index = 0; src_index < src_length; ) {
2669     dest[dest_index++] = src[src_index++];
2670   }
2671 
2672   // If we have a hash, append it
2673   for (int hash_index = 0; hash_index < hash_len; ) {
2674     dest[dest_index++] = hash_buf[hash_index++];
2675   }
2676 
2677   // Add the semicolon and the NULL
2678   dest[dest_index++] = ';';
2679   dest[dest_index] = '\0';
2680   return dest;
2681 }
2682 
2683 // different verisons of is_same_class_package
2684 bool InstanceKlass::is_same_class_package(Klass* class2) {
2685   Klass* class1 = this;
2686   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
2687   Symbol* classname1 = class1->name();
2688 
2689   if (class2->oop_is_objArray()) {
2690     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
2691   }
2692   oop classloader2;
2693   if (class2->oop_is_instance()) {
2694     classloader2 = InstanceKlass::cast(class2)->class_loader();
2695   } else {
2696     assert(class2->oop_is_typeArray(), "should be type array");
2697     classloader2 = NULL;
2698   }
2699   Symbol* classname2 = class2->name();
2700 
2701   return InstanceKlass::is_same_class_package(classloader1, classname1,
2702                                               classloader2, classname2);
2703 }
2704 
2705 bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
2706   Klass* class1 = this;
2707   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
2708   Symbol* classname1 = class1->name();
2709 
2710   return InstanceKlass::is_same_class_package(classloader1, classname1,
2711                                               classloader2, classname2);
2712 }
2713 
2714 // return true if two classes are in the same package, classloader
2715 // and classname information is enough to determine a class's package
2716 bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
2717                                           oop class_loader2, Symbol* class_name2) {
2718   if (class_loader1 != class_loader2) {
2719     return false;
2720   } else if (class_name1 == class_name2) {
2721     return true;                // skip painful bytewise comparison
2722   } else {
2723     ResourceMark rm;
2724 
2725     // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly
2726     // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
2727     // Otherwise, we just compare jbyte values between the strings.
2728     const jbyte *name1 = class_name1->base();
2729     const jbyte *name2 = class_name2->base();
2730 
2731     const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
2732     const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
2733 
2734     if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
2735       // One of the two doesn't have a package.  Only return true
2736       // if the other one also doesn't have a package.
2737       return last_slash1 == last_slash2;
2738     } else {
2739       // Skip over '['s
2740       if (*name1 == '[') {
2741         do {
2742           name1++;
2743         } while (*name1 == '[');
2744         if (*name1 != 'L') {
2745           // Something is terribly wrong.  Shouldn't be here.
2746           return false;
2747         }
2748       }
2749       if (*name2 == '[') {
2750         do {
2751           name2++;
2752         } while (*name2 == '[');
2753         if (*name2 != 'L') {
2754           // Something is terribly wrong.  Shouldn't be here.
2755           return false;
2756         }
2757       }
2758 
2759       // Check that package part is identical
2760       int length1 = last_slash1 - name1;
2761       int length2 = last_slash2 - name2;
2762 
2763       return UTF8::equal(name1, length1, name2, length2);
2764     }
2765   }
2766 }
2767 
2768 // Returns true iff super_method can be overridden by a method in targetclassname
2769 // See JSL 3rd edition 8.4.6.1
2770 // Assumes name-signature match
2771 // "this" is InstanceKlass of super_method which must exist
2772 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
2773 bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
2774    // Private methods can not be overridden
2775    if (super_method->is_private()) {
2776      return false;
2777    }
2778    // If super method is accessible, then override
2779    if ((super_method->is_protected()) ||
2780        (super_method->is_public())) {
2781      return true;
2782    }
2783    // Package-private methods are not inherited outside of package
2784    assert(super_method->is_package_private(), "must be package private");
2785    return(is_same_class_package(targetclassloader(), targetclassname));
2786 }
2787 
2788 /* defined for now in jvm.cpp, for historical reasons *--
2789 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
2790                                                      Symbol*& simple_name_result, TRAPS) {
2791   ...
2792 }
2793 */
2794 
2795 // tell if two classes have the same enclosing class (at package level)
2796 bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
2797                                                 Klass* class2_oop, TRAPS) {
2798   if (class2_oop == class1())                       return true;
2799   if (!class2_oop->oop_is_instance())  return false;
2800   instanceKlassHandle class2(THREAD, class2_oop);
2801 
2802   // must be in same package before we try anything else
2803   if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
2804     return false;
2805 
2806   // As long as there is an outer1.getEnclosingClass,
2807   // shift the search outward.
2808   instanceKlassHandle outer1 = class1;
2809   for (;;) {
2810     // As we walk along, look for equalities between outer1 and class2.
2811     // Eventually, the walks will terminate as outer1 stops
2812     // at the top-level class around the original class.
2813     bool ignore_inner_is_member;
2814     Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
2815                                                     CHECK_false);
2816     if (next == NULL)  break;
2817     if (next == class2())  return true;
2818     outer1 = instanceKlassHandle(THREAD, next);
2819   }
2820 
2821   // Now do the same for class2.
2822   instanceKlassHandle outer2 = class2;
2823   for (;;) {
2824     bool ignore_inner_is_member;
2825     Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
2826                                                     CHECK_false);
2827     if (next == NULL)  break;
2828     // Might as well check the new outer against all available values.
2829     if (next == class1())  return true;
2830     if (next == outer1())  return true;
2831     outer2 = instanceKlassHandle(THREAD, next);
2832   }
2833 
2834   // If by this point we have not found an equality between the
2835   // two classes, we know they are in separate package members.
2836   return false;
2837 }
2838 
2839 
2840 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
2841   jint access = access_flags().as_int();
2842 
2843   // But check if it happens to be member class.
2844   instanceKlassHandle ik(THREAD, this);
2845   InnerClassesIterator iter(ik);
2846   for (; !iter.done(); iter.next()) {
2847     int ioff = iter.inner_class_info_index();
2848     // Inner class attribute can be zero, skip it.
2849     // Strange but true:  JVM spec. allows null inner class refs.
2850     if (ioff == 0) continue;
2851 
2852     // only look at classes that are already loaded
2853     // since we are looking for the flags for our self.
2854     Symbol* inner_name = ik->constants()->klass_name_at(ioff);
2855     if ((ik->name() == inner_name)) {
2856       // This is really a member class.
2857       access = iter.inner_access_flags();
2858       break;
2859     }
2860   }
2861   // Remember to strip ACC_SUPER bit
2862   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
2863 }
2864 
2865 jint InstanceKlass::jvmti_class_status() const {
2866   jint result = 0;
2867 
2868   if (is_linked()) {
2869     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
2870   }
2871 
2872   if (is_initialized()) {
2873     assert(is_linked(), "Class status is not consistent");
2874     result |= JVMTI_CLASS_STATUS_INITIALIZED;
2875   }
2876   if (is_in_error_state()) {
2877     result |= JVMTI_CLASS_STATUS_ERROR;
2878   }
2879   return result;
2880 }
2881 
2882 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
2883   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2884   int method_table_offset_in_words = ioe->offset()/wordSize;
2885   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2886                        / itableOffsetEntry::size();
2887 
2888   for (int cnt = 0 ; ; cnt ++, ioe ++) {
2889     // If the interface isn't implemented by the receiver class,
2890     // the VM should throw IncompatibleClassChangeError.
2891     if (cnt >= nof_interfaces) {
2892       THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
2893     }
2894 
2895     Klass* ik = ioe->interface_klass();
2896     if (ik == holder) break;
2897   }
2898 
2899   itableMethodEntry* ime = ioe->first_method_entry(this);
2900   Method* m = ime[index].method();
2901   if (m == NULL) {
2902     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
2903   }
2904   return m;
2905 }
2906 
2907 
2908 #if INCLUDE_JVMTI
2909 // update default_methods for redefineclasses for methods that are
2910 // not yet in the vtable due to concurrent subclass define and superinterface
2911 // redefinition
2912 // Note: those in the vtable, should have been updated via adjust_method_entries
2913 void InstanceKlass::adjust_default_methods(InstanceKlass* holder, bool* trace_name_printed) {
2914   // search the default_methods for uses of either obsolete or EMCP methods
2915   if (default_methods() != NULL) {
2916     for (int index = 0; index < default_methods()->length(); index ++) {
2917       Method* old_method = default_methods()->at(index);
2918       if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) {
2919         continue; // skip uninteresting entries
2920       }
2921       assert(!old_method->is_deleted(), "default methods may not be deleted");
2922 
2923       Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum());
2924 
2925       assert(new_method != NULL, "method_with_idnum() should not be NULL");
2926       assert(old_method != new_method, "sanity check");
2927 
2928       default_methods()->at_put(index, new_method);
2929       if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
2930         if (!(*trace_name_printed)) {
2931           // RC_TRACE_MESG macro has an embedded ResourceMark
2932           RC_TRACE_MESG(("adjust: klassname=%s default methods from name=%s",
2933                          external_name(),
2934                          old_method->method_holder()->external_name()));
2935           *trace_name_printed = true;
2936         }
2937         RC_TRACE(0x00100000, ("default method update: %s(%s) ",
2938                               new_method->name()->as_C_string(),
2939                               new_method->signature()->as_C_string()));
2940       }
2941     }
2942   }
2943 }
2944 #endif // INCLUDE_JVMTI
2945 
2946 // On-stack replacement stuff
2947 void InstanceKlass::add_osr_nmethod(nmethod* n) {
2948 #ifndef PRODUCT
2949   if (TieredCompilation) {
2950       nmethod * prev = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), n->comp_level(), true);
2951       assert(prev == NULL || !prev->is_in_use(),
2952       "redundunt OSR recompilation detected. memory leak in CodeCache!");
2953   }
2954 #endif
2955   // only one compilation can be active
2956   NEEDS_CLEANUP
2957   // This is a short non-blocking critical region, so the no safepoint check is ok.
2958   OsrList_lock->lock_without_safepoint_check();
2959   assert(n->is_osr_method(), "wrong kind of nmethod");
2960   n->set_osr_link(osr_nmethods_head());
2961   set_osr_nmethods_head(n);
2962   // Raise the highest osr level if necessary
2963   if (TieredCompilation) {
2964     Method* m = n->method();
2965     m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
2966   }
2967   // Remember to unlock again
2968   OsrList_lock->unlock();
2969 
2970   // Get rid of the osr methods for the same bci that have lower levels.
2971   if (TieredCompilation) {
2972     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
2973       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
2974       if (inv != NULL && inv->is_in_use()) {
2975         inv->make_not_entrant();
2976       }
2977     }
2978   }
2979 }
2980 
2981 
2982 void InstanceKlass::remove_osr_nmethod(nmethod* n) {
2983   // This is a short non-blocking critical region, so the no safepoint check is ok.
2984   OsrList_lock->lock_without_safepoint_check();
2985   assert(n->is_osr_method(), "wrong kind of nmethod");
2986   nmethod* last = NULL;
2987   nmethod* cur  = osr_nmethods_head();
2988   int max_level = CompLevel_none;  // Find the max comp level excluding n
2989   Method* m = n->method();
2990   // Search for match
2991   while(cur != NULL && cur != n) {
2992     if (TieredCompilation && m == cur->method()) {
2993       // Find max level before n
2994       max_level = MAX2(max_level, cur->comp_level());
2995     }
2996     last = cur;
2997     cur = cur->osr_link();
2998   }
2999   nmethod* next = NULL;
3000   if (cur == n) {
3001     next = cur->osr_link();
3002     if (last == NULL) {
3003       // Remove first element
3004       set_osr_nmethods_head(next);
3005     } else {
3006       last->set_osr_link(next);
3007     }
3008   }
3009   n->set_osr_link(NULL);
3010   if (TieredCompilation) {
3011     cur = next;
3012     while (cur != NULL) {
3013       // Find max level after n
3014       if (m == cur->method()) {
3015         max_level = MAX2(max_level, cur->comp_level());
3016       }
3017       cur = cur->osr_link();
3018     }
3019     m->set_highest_osr_comp_level(max_level);
3020   }
3021   // Remember to unlock again
3022   OsrList_lock->unlock();
3023 }
3024 
3025 int InstanceKlass::mark_osr_nmethods(const Method* m) {
3026   // This is a short non-blocking critical region, so the no safepoint check is ok.
3027   MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
3028   nmethod* osr = osr_nmethods_head();
3029   int found = 0;
3030   while (osr != NULL) {
3031     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3032     if (osr->method() == m) {
3033       osr->mark_for_deoptimization();
3034       found++;
3035     }
3036     osr = osr->osr_link();
3037   }
3038   return found;
3039 }
3040 
3041 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
3042   // This is a short non-blocking critical region, so the no safepoint check is ok.
3043   OsrList_lock->lock_without_safepoint_check();
3044   nmethod* osr = osr_nmethods_head();
3045   nmethod* best = NULL;
3046   while (osr != NULL) {
3047     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3048     // There can be a time when a c1 osr method exists but we are waiting
3049     // for a c2 version. When c2 completes its osr nmethod we will trash
3050     // the c1 version and only be able to find the c2 version. However
3051     // while we overflow in the c1 code at back branches we don't want to
3052     // try and switch to the same code as we are already running
3053 
3054     if (osr->method() == m &&
3055         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
3056       if (match_level) {
3057         if (osr->comp_level() == comp_level) {
3058           // Found a match - return it.
3059           OsrList_lock->unlock();
3060           return osr;
3061         }
3062       } else {
3063         if (best == NULL || (osr->comp_level() > best->comp_level())) {
3064           if (osr->comp_level() == CompLevel_highest_tier) {
3065             // Found the best possible - return it.
3066             OsrList_lock->unlock();
3067             return osr;
3068           }
3069           best = osr;
3070         }
3071       }
3072     }
3073     osr = osr->osr_link();
3074   }
3075   OsrList_lock->unlock();
3076 
3077   assert(match_level == false || best == NULL, "shouldn't pick up anything if match_level is set");
3078   if (best != NULL && best->comp_level() >= comp_level) {
3079     return best;
3080   }
3081   return NULL;
3082 }
3083 
3084 oop InstanceKlass::add_member_name(Handle mem_name, bool intern) {
3085   jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);
3086   MutexLocker ml(MemberNameTable_lock);
3087   DEBUG_ONLY(No_Safepoint_Verifier nsv);
3088 
3089   // Check if method has been redefined while taking out MemberNameTable_lock, if so
3090   // return false.  We cannot cache obsolete methods. They will crash when the function
3091   // is called!
3092   Method* method = (Method*)java_lang_invoke_MemberName::vmtarget(mem_name());
3093   if (method->is_obsolete()) {
3094     return NULL;
3095   } else if (method->is_old()) {
3096     // Replace method with redefined version
3097     java_lang_invoke_MemberName::set_vmtarget(mem_name(), method_with_idnum(method->method_idnum()));
3098   }
3099 
3100   if (_member_names == NULL) {
3101     _member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count());
3102   }
3103   if (intern) {
3104     return _member_names->find_or_add_member_name(mem_name_wref);
3105   } else {
3106     return _member_names->add_member_name(mem_name_wref);
3107   }
3108 }
3109 
3110 // -----------------------------------------------------------------------------------------------------
3111 // Printing
3112 
3113 #ifndef PRODUCT
3114 
3115 #define BULLET  " - "
3116 
3117 static const char* state_names[] = {
3118   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3119 };
3120 
3121 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3122   for (int i = 0; i < len; i++) {
3123     intptr_t e = start[i];
3124     st->print("%d : " INTPTR_FORMAT, i, e);
3125     if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {
3126       st->print(" ");
3127       ((Metadata*)e)->print_value_on(st);
3128     }
3129     st->cr();
3130   }
3131 }
3132 
3133 void InstanceKlass::print_on(outputStream* st) const {
3134   assert(is_klass(), "must be klass");
3135   Klass::print_on(st);
3136 
3137   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3138   st->print(BULLET"klass size:        %d", size());                               st->cr();
3139   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
3140   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
3141   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3142   st->print(BULLET"super:             "); super()->print_value_on_maybe_null(st); st->cr();
3143   st->print(BULLET"sub:               ");
3144   Klass* sub = subklass();
3145   int n;
3146   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
3147     if (n < MaxSubklassPrintSize) {
3148       sub->print_value_on(st);
3149       st->print("   ");
3150     }
3151   }
3152   if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);
3153   st->cr();
3154 
3155   if (is_interface()) {
3156     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
3157     if (nof_implementors() == 1) {
3158       st->print_cr(BULLET"implementor:    ");
3159       st->print("   ");
3160       implementor()->print_value_on(st);
3161       st->cr();
3162     }
3163   }
3164 
3165   st->print(BULLET"arrays:            "); array_klasses()->print_value_on_maybe_null(st); st->cr();
3166   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
3167   if (Verbose || WizardMode) {
3168     Array<Method*>* method_array = methods();
3169     for (int i = 0; i < method_array->length(); i++) {
3170       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3171     }
3172   }
3173   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
3174   st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
3175   if (Verbose && default_methods() != NULL) {
3176     Array<Method*>* method_array = default_methods();
3177     for (int i = 0; i < method_array->length(); i++) {
3178       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3179     }
3180   }
3181   if (default_vtable_indices() != NULL) {
3182     st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
3183   }
3184   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
3185   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3186   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
3187   if (class_loader_data() != NULL) {
3188     st->print(BULLET"class loader data:  ");
3189     class_loader_data()->print_value_on(st);
3190     st->cr();
3191   }
3192   st->print(BULLET"host class:        "); host_klass()->print_value_on_maybe_null(st); st->cr();
3193   if (source_file_name() != NULL) {
3194     st->print(BULLET"source file:       ");
3195     source_file_name()->print_value_on(st);
3196     st->cr();
3197   }
3198   if (source_debug_extension() != NULL) {
3199     st->print(BULLET"source debug extension:       ");
3200     st->print("%s", source_debug_extension());
3201     st->cr();
3202   }
3203   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
3204   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
3205   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
3206   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
3207   {
3208     bool have_pv = false;
3209     // previous versions are linked together through the InstanceKlass
3210     for (InstanceKlass* pv_node = _previous_versions;
3211          pv_node != NULL;
3212          pv_node = pv_node->previous_versions()) {
3213       if (!have_pv)
3214         st->print(BULLET"previous version:  ");
3215       have_pv = true;
3216       pv_node->constants()->print_value_on(st);
3217     }
3218     if (have_pv) st->cr();
3219   }
3220 
3221   if (generic_signature() != NULL) {
3222     st->print(BULLET"generic signature: ");
3223     generic_signature()->print_value_on(st);
3224     st->cr();
3225   }
3226   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
3227   st->print(BULLET"java mirror:       "); java_mirror()->print_value_on(st);       st->cr();
3228   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable());  st->cr();
3229   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
3230   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();
3231   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
3232   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3233   FieldPrinter print_static_field(st);
3234   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3235   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3236   FieldPrinter print_nonstatic_field(st);
3237   ((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);
3238 
3239   st->print(BULLET"non-static oop maps: ");
3240   OopMapBlock* map     = start_of_nonstatic_oop_maps();
3241   OopMapBlock* end_map = map + nonstatic_oop_map_count();
3242   while (map < end_map) {
3243     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3244     map++;
3245   }
3246   st->cr();
3247 }
3248 
3249 #endif //PRODUCT
3250 
3251 void InstanceKlass::print_value_on(outputStream* st) const {
3252   assert(is_klass(), "must be klass");
3253   if (Verbose || WizardMode)  access_flags().print_on(st);
3254   name()->print_value_on(st);
3255 }
3256 
3257 #ifndef PRODUCT
3258 
3259 void FieldPrinter::do_field(fieldDescriptor* fd) {
3260   _st->print(BULLET);
3261    if (_obj == NULL) {
3262      fd->print_on(_st);
3263      _st->cr();
3264    } else {
3265      fd->print_on_for(_st, _obj);
3266      _st->cr();
3267    }
3268 }
3269 
3270 
3271 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3272   Klass::oop_print_on(obj, st);
3273 
3274   if (this == SystemDictionary::String_klass()) {
3275     typeArrayOop value  = java_lang_String::value(obj);
3276     juint        offset = java_lang_String::offset(obj);
3277     juint        length = java_lang_String::length(obj);
3278     if (value != NULL &&
3279         value->is_typeArray() &&
3280         offset          <= (juint) value->length() &&
3281         offset + length <= (juint) value->length()) {
3282       st->print(BULLET"string: ");
3283       java_lang_String::print(obj, st);
3284       st->cr();
3285       if (!WizardMode)  return;  // that is enough
3286     }
3287   }
3288 
3289   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
3290   FieldPrinter print_field(st, obj);
3291   do_nonstatic_fields(&print_field);
3292 
3293   if (this == SystemDictionary::Class_klass()) {
3294     st->print(BULLET"signature: ");
3295     java_lang_Class::print_signature(obj, st);
3296     st->cr();
3297     Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
3298     st->print(BULLET"fake entry for mirror: ");
3299     mirrored_klass->print_value_on_maybe_null(st);
3300     st->cr();
3301     Klass* array_klass = java_lang_Class::array_klass(obj);
3302     st->print(BULLET"fake entry for array: ");
3303     array_klass->print_value_on_maybe_null(st);
3304     st->cr();
3305     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
3306     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
3307     Klass* real_klass = java_lang_Class::as_Klass(obj);
3308     if (real_klass != NULL && real_klass->oop_is_instance()) {
3309       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3310     }
3311   } else if (this == SystemDictionary::MethodType_klass()) {
3312     st->print(BULLET"signature: ");
3313     java_lang_invoke_MethodType::print_signature(obj, st);
3314     st->cr();
3315   }
3316 }
3317 
3318 #endif //PRODUCT
3319 
3320 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
3321   st->print("a ");
3322   name()->print_value_on(st);
3323   obj->print_address_on(st);
3324   if (this == SystemDictionary::String_klass()
3325       && java_lang_String::value(obj) != NULL) {
3326     ResourceMark rm;
3327     int len = java_lang_String::length(obj);
3328     int plen = (len < 24 ? len : 12);
3329     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
3330     st->print(" = \"%s\"", str);
3331     if (len > plen)
3332       st->print("...[%d]", len);
3333   } else if (this == SystemDictionary::Class_klass()) {
3334     Klass* k = java_lang_Class::as_Klass(obj);
3335     st->print(" = ");
3336     if (k != NULL) {
3337       k->print_value_on(st);
3338     } else {
3339       const char* tname = type2name(java_lang_Class::primitive_type(obj));
3340       st->print("%s", tname ? tname : "type?");
3341     }
3342   } else if (this == SystemDictionary::MethodType_klass()) {
3343     st->print(" = ");
3344     java_lang_invoke_MethodType::print_signature(obj, st);
3345   } else if (java_lang_boxing_object::is_instance(obj)) {
3346     st->print(" = ");
3347     java_lang_boxing_object::print(obj, st);
3348   } else if (this == SystemDictionary::LambdaForm_klass()) {
3349     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
3350     if (vmentry != NULL) {
3351       st->print(" => ");
3352       vmentry->print_value_on(st);
3353     }
3354   } else if (this == SystemDictionary::MemberName_klass()) {
3355     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
3356     if (vmtarget != NULL) {
3357       st->print(" = ");
3358       vmtarget->print_value_on(st);
3359     } else {
3360       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
3361       st->print(".");
3362       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
3363     }
3364   }
3365 }
3366 
3367 const char* InstanceKlass::internal_name() const {
3368   return external_name();
3369 }
3370 
3371 #if INCLUDE_SERVICES
3372 // Size Statistics
3373 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
3374   Klass::collect_statistics(sz);
3375 
3376   sz->_inst_size  = HeapWordSize * size_helper();
3377   sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());
3378   sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());
3379   sz->_nonstatic_oopmap_bytes = HeapWordSize *
3380         ((is_interface() || is_anonymous()) ?
3381          align_object_offset(nonstatic_oop_map_size()) :
3382          nonstatic_oop_map_size());
3383 
3384   int n = 0;
3385   n += (sz->_methods_array_bytes         = sz->count_array(methods()));
3386   n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
3387   n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
3388   n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
3389   n += (sz->_fields_bytes                = sz->count_array(fields()));
3390   n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
3391   sz->_ro_bytes += n;
3392 
3393   const ConstantPool* cp = constants();
3394   if (cp) {
3395     cp->collect_statistics(sz);
3396   }
3397 
3398   const Annotations* anno = annotations();
3399   if (anno) {
3400     anno->collect_statistics(sz);
3401   }
3402 
3403   const Array<Method*>* methods_array = methods();
3404   if (methods()) {
3405     for (int i = 0; i < methods_array->length(); i++) {
3406       Method* method = methods_array->at(i);
3407       if (method) {
3408         sz->_method_count ++;
3409         method->collect_statistics(sz);
3410       }
3411     }
3412   }
3413 }
3414 #endif // INCLUDE_SERVICES
3415 
3416 // Verification
3417 
3418 class VerifyFieldClosure: public OopClosure {
3419  protected:
3420   template <class T> void do_oop_work(T* p) {
3421     oop obj = oopDesc::load_decode_heap_oop(p);
3422     if (!obj->is_oop_or_null()) {
3423       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);
3424       Universe::print();
3425       guarantee(false, "boom");
3426     }
3427   }
3428  public:
3429   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
3430   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
3431 };
3432 
3433 void InstanceKlass::verify_on(outputStream* st) {
3434 #ifndef PRODUCT
3435   // Avoid redundant verifies, this really should be in product.
3436   if (_verify_count == Universe::verify_count()) return;
3437   _verify_count = Universe::verify_count();
3438 #endif
3439 
3440   // Verify Klass
3441   Klass::verify_on(st);
3442 
3443   // Verify that klass is present in ClassLoaderData
3444   guarantee(class_loader_data()->contains_klass(this),
3445             "this class isn't found in class loader data");
3446 
3447   // Verify vtables
3448   if (is_linked()) {
3449     ResourceMark rm;
3450     // $$$ This used to be done only for m/s collections.  Doing it
3451     // always seemed a valid generalization.  (DLD -- 6/00)
3452     vtable()->verify(st);
3453   }
3454 
3455   // Verify first subklass
3456   if (subklass_oop() != NULL) {
3457     guarantee(subklass_oop()->is_klass(), "should be klass");
3458   }
3459 
3460   // Verify siblings
3461   Klass* super = this->super();
3462   Klass* sib = next_sibling();
3463   if (sib != NULL) {
3464     if (sib == this) {
3465       fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));
3466     }
3467 
3468     guarantee(sib->is_klass(), "should be klass");
3469     guarantee(sib->super() == super, "siblings should have same superklass");
3470   }
3471 
3472   // Verify implementor fields
3473   Klass* im = implementor();
3474   if (im != NULL) {
3475     guarantee(is_interface(), "only interfaces should have implementor set");
3476     guarantee(im->is_klass(), "should be klass");
3477     guarantee(!im->is_interface() || im == this,
3478       "implementors cannot be interfaces");
3479   }
3480 
3481   // Verify local interfaces
3482   if (local_interfaces()) {
3483     Array<Klass*>* local_interfaces = this->local_interfaces();
3484     for (int j = 0; j < local_interfaces->length(); j++) {
3485       Klass* e = local_interfaces->at(j);
3486       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
3487     }
3488   }
3489 
3490   // Verify transitive interfaces
3491   if (transitive_interfaces() != NULL) {
3492     Array<Klass*>* transitive_interfaces = this->transitive_interfaces();
3493     for (int j = 0; j < transitive_interfaces->length(); j++) {
3494       Klass* e = transitive_interfaces->at(j);
3495       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
3496     }
3497   }
3498 
3499   // Verify methods
3500   if (methods() != NULL) {
3501     Array<Method*>* methods = this->methods();
3502     for (int j = 0; j < methods->length(); j++) {
3503       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3504     }
3505     for (int j = 0; j < methods->length() - 1; j++) {
3506       Method* m1 = methods->at(j);
3507       Method* m2 = methods->at(j + 1);
3508       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3509     }
3510   }
3511 
3512   // Verify method ordering
3513   if (method_ordering() != NULL) {
3514     Array<int>* method_ordering = this->method_ordering();
3515     int length = method_ordering->length();
3516     if (JvmtiExport::can_maintain_original_method_order() ||
3517         ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
3518       guarantee(length == methods()->length(), "invalid method ordering length");
3519       jlong sum = 0;
3520       for (int j = 0; j < length; j++) {
3521         int original_index = method_ordering->at(j);
3522         guarantee(original_index >= 0, "invalid method ordering index");
3523         guarantee(original_index < length, "invalid method ordering index");
3524         sum += original_index;
3525       }
3526       // Verify sum of indices 0,1,...,length-1
3527       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
3528     } else {
3529       guarantee(length == 0, "invalid method ordering length");
3530     }
3531   }
3532 
3533   // Verify default methods
3534   if (default_methods() != NULL) {
3535     Array<Method*>* methods = this->default_methods();
3536     for (int j = 0; j < methods->length(); j++) {
3537       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3538     }
3539     for (int j = 0; j < methods->length() - 1; j++) {
3540       Method* m1 = methods->at(j);
3541       Method* m2 = methods->at(j + 1);
3542       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3543     }
3544   }
3545 
3546   // Verify JNI static field identifiers
3547   if (jni_ids() != NULL) {
3548     jni_ids()->verify(this);
3549   }
3550 
3551   // Verify other fields
3552   if (array_klasses() != NULL) {
3553     guarantee(array_klasses()->is_klass(), "should be klass");
3554   }
3555   if (constants() != NULL) {
3556     guarantee(constants()->is_constantPool(), "should be constant pool");
3557   }
3558   const Klass* host = host_klass();
3559   if (host != NULL) {
3560     guarantee(host->is_klass(), "should be klass");
3561   }
3562 }
3563 
3564 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
3565   Klass::oop_verify_on(obj, st);
3566   VerifyFieldClosure blk;
3567   obj->oop_iterate_no_header(&blk);
3568 }
3569 
3570 
3571 // JNIid class for jfieldIDs only
3572 // Note to reviewers:
3573 // These JNI functions are just moved over to column 1 and not changed
3574 // in the compressed oops workspace.
3575 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
3576   _holder = holder;
3577   _offset = offset;
3578   _next = next;
3579   debug_only(_is_static_field_id = false;)
3580 }
3581 
3582 
3583 JNIid* JNIid::find(int offset) {
3584   JNIid* current = this;
3585   while (current != NULL) {
3586     if (current->offset() == offset) return current;
3587     current = current->next();
3588   }
3589   return NULL;
3590 }
3591 
3592 void JNIid::deallocate(JNIid* current) {
3593   while (current != NULL) {
3594     JNIid* next = current->next();
3595     delete current;
3596     current = next;
3597   }
3598 }
3599 
3600 
3601 void JNIid::verify(Klass* holder) {
3602   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
3603   int end_field_offset;
3604   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
3605 
3606   JNIid* current = this;
3607   while (current != NULL) {
3608     guarantee(current->holder() == holder, "Invalid klass in JNIid");
3609 #ifdef ASSERT
3610     int o = current->offset();
3611     if (current->is_static_field_id()) {
3612       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
3613     }
3614 #endif
3615     current = current->next();
3616   }
3617 }
3618 
3619 
3620 #ifdef ASSERT
3621 void InstanceKlass::set_init_state(ClassState state) {
3622   bool good_state = is_shared() ? (_init_state <= state)
3623                                                : (_init_state < state);
3624   assert(good_state || state == allocated, "illegal state transition");
3625   assert(_init_thread == NULL, "should be cleared before state change");
3626   _init_state = (u1)state;
3627 }
3628 #endif
3629 
3630 
3631 // RedefineClasses() support for previous versions:
3632 
3633 // Purge previous versions
3634 void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
3635   if (ik->previous_versions() != NULL) {
3636     // This klass has previous versions so see what we can cleanup
3637     // while it is safe to do so.
3638 
3639     int deleted_count = 0;    // leave debugging breadcrumbs
3640     int live_count = 0;
3641     ClassLoaderData* loader_data = ik->class_loader_data();
3642     assert(loader_data != NULL, "should never be null");
3643 
3644     // RC_TRACE macro has an embedded ResourceMark
3645     RC_TRACE(0x00000200, ("purge: %s: previous versions", ik->external_name()));
3646 
3647     // previous versions are linked together through the InstanceKlass
3648     InstanceKlass* pv_node = ik->previous_versions();
3649     InstanceKlass* last = ik;
3650     int version = 0;
3651 
3652     // check the previous versions list
3653     for (; pv_node != NULL; ) {
3654 
3655       ConstantPool* pvcp = pv_node->constants();
3656       assert(pvcp != NULL, "cp ref was unexpectedly cleared");
3657 
3658 
3659       if (!pvcp->on_stack()) {
3660         // If the constant pool isn't on stack, none of the methods
3661         // are executing.  Unlink this previous_version.
3662         // The previous version InstanceKlass is on the ClassLoaderData deallocate list
3663         // so will be deallocated during the next phase of class unloading.
3664         pv_node = pv_node->previous_versions();
3665         last->link_previous_versions(pv_node);
3666         deleted_count++;
3667         version++;
3668         continue;
3669       } else {
3670         RC_TRACE(0x00000200, ("purge: previous version " INTPTR_FORMAT " is alive",
3671                               pv_node));
3672         assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
3673         guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
3674         live_count++;
3675       }
3676 
3677       // At least one method is live in this previous version so clean its MethodData.
3678       // Reset dead EMCP methods not to get breakpoints.
3679       // All methods are deallocated when all of the methods for this class are no
3680       // longer running.
3681       Array<Method*>* method_refs = pv_node->methods();
3682       if (method_refs != NULL) {
3683         RC_TRACE(0x00000200, ("purge: previous methods length=%d",
3684           method_refs->length()));
3685         for (int j = 0; j < method_refs->length(); j++) {
3686           Method* method = method_refs->at(j);
3687 
3688           if (!method->on_stack()) {
3689             // no breakpoints for non-running methods
3690             if (method->is_running_emcp()) {
3691               method->set_running_emcp(false);
3692             }
3693           } else {
3694             assert (method->is_obsolete() || method->is_running_emcp(),
3695                     "emcp method cannot run after emcp bit is cleared");
3696             // RC_TRACE macro has an embedded ResourceMark
3697             RC_TRACE(0x00000200,
3698               ("purge: %s(%s): prev method @%d in version @%d is alive",
3699               method->name()->as_C_string(),
3700               method->signature()->as_C_string(), j, version));
3701             if (method->method_data() != NULL) {
3702               // Clean out any weak method links for running methods
3703               // (also should include not EMCP methods)
3704               method->method_data()->clean_weak_method_links();
3705             }
3706           }
3707         }
3708       }
3709       // next previous version
3710       last = pv_node;
3711       pv_node = pv_node->previous_versions();
3712       version++;
3713     }
3714     RC_TRACE(0x00000200,
3715       ("purge: previous version stats: live=%d, deleted=%d", live_count,
3716       deleted_count));
3717   }
3718 
3719   // Clean MethodData of this class's methods so they don't refer to
3720   // old methods that are no longer running.
3721   Array<Method*>* methods = ik->methods();
3722   int num_methods = methods->length();
3723   for (int index2 = 0; index2 < num_methods; ++index2) {
3724     if (methods->at(index2)->method_data() != NULL) {
3725       methods->at(index2)->method_data()->clean_weak_method_links();
3726     }
3727   }
3728 }
3729 
3730 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,
3731                                                 int emcp_method_count) {
3732   int obsolete_method_count = old_methods->length() - emcp_method_count;
3733 
3734   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
3735       _previous_versions != NULL) {
3736     // We have a mix of obsolete and EMCP methods so we have to
3737     // clear out any matching EMCP method entries the hard way.
3738     int local_count = 0;
3739     for (int i = 0; i < old_methods->length(); i++) {
3740       Method* old_method = old_methods->at(i);
3741       if (old_method->is_obsolete()) {
3742         // only obsolete methods are interesting
3743         Symbol* m_name = old_method->name();
3744         Symbol* m_signature = old_method->signature();
3745 
3746         // previous versions are linked together through the InstanceKlass
3747         int j = 0;
3748         for (InstanceKlass* prev_version = _previous_versions;
3749              prev_version != NULL;
3750              prev_version = prev_version->previous_versions(), j++) {
3751 
3752           Array<Method*>* method_refs = prev_version->methods();
3753           for (int k = 0; k < method_refs->length(); k++) {
3754             Method* method = method_refs->at(k);
3755 
3756             if (!method->is_obsolete() &&
3757                 method->name() == m_name &&
3758                 method->signature() == m_signature) {
3759               // The current RedefineClasses() call has made all EMCP
3760               // versions of this method obsolete so mark it as obsolete
3761               RC_TRACE(0x00000400,
3762                 ("add: %s(%s): flush obsolete method @%d in version @%d",
3763                 m_name->as_C_string(), m_signature->as_C_string(), k, j));
3764 
3765               method->set_is_obsolete();
3766               break;
3767             }
3768           }
3769 
3770           // The previous loop may not find a matching EMCP method, but
3771           // that doesn't mean that we can optimize and not go any
3772           // further back in the PreviousVersion generations. The EMCP
3773           // method for this generation could have already been made obsolete,
3774           // but there still may be an older EMCP method that has not
3775           // been made obsolete.
3776         }
3777 
3778         if (++local_count >= obsolete_method_count) {
3779           // no more obsolete methods so bail out now
3780           break;
3781         }
3782       }
3783     }
3784   }
3785 }
3786 
3787 // Save the scratch_class as the previous version if any of the methods are running.
3788 // The previous_versions are used to set breakpoints in EMCP methods and they are
3789 // also used to clean MethodData links to redefined methods that are no longer running.
3790 void InstanceKlass::add_previous_version(instanceKlassHandle scratch_class,
3791                                          int emcp_method_count) {
3792   assert(Thread::current()->is_VM_thread(),
3793          "only VMThread can add previous versions");
3794 
3795   // RC_TRACE macro has an embedded ResourceMark
3796   RC_TRACE(0x00000400, ("adding previous version ref for %s, EMCP_cnt=%d",
3797     scratch_class->external_name(), emcp_method_count));
3798 
3799   // Clean out old previous versions
3800   purge_previous_versions(this);
3801 
3802   // Mark newly obsolete methods in remaining previous versions.  An EMCP method from
3803   // a previous redefinition may be made obsolete by this redefinition.
3804   Array<Method*>* old_methods = scratch_class->methods();
3805   mark_newly_obsolete_methods(old_methods, emcp_method_count);
3806 
3807   // If the constant pool for this previous version of the class
3808   // is not marked as being on the stack, then none of the methods
3809   // in this previous version of the class are on the stack so
3810   // we don't need to add this as a previous version.
3811   ConstantPool* cp_ref = scratch_class->constants();
3812   if (!cp_ref->on_stack()) {
3813     RC_TRACE(0x00000400, ("add: scratch class not added; no methods are running"));
3814     return;
3815   }
3816 
3817   if (emcp_method_count != 0) {
3818     // At least one method is still running, check for EMCP methods
3819     for (int i = 0; i < old_methods->length(); i++) {
3820       Method* old_method = old_methods->at(i);
3821       if (!old_method->is_obsolete() && old_method->on_stack()) {
3822         // if EMCP method (not obsolete) is on the stack, mark as EMCP so that
3823         // we can add breakpoints for it.
3824 
3825         // We set the method->on_stack bit during safepoints for class redefinition and
3826         // class unloading and use this bit to set the is_running_emcp bit.
3827         // After the safepoint, the on_stack bit is cleared and the running emcp
3828         // method may exit.   If so, we would set a breakpoint in a method that
3829         // is never reached, but this won't be noticeable to the programmer.
3830         old_method->set_running_emcp(true);
3831         RC_TRACE(0x00000400, ("add: EMCP method %s is on_stack " INTPTR_FORMAT,
3832                               old_method->name_and_sig_as_C_string(), old_method));
3833       } else if (!old_method->is_obsolete()) {
3834         RC_TRACE(0x00000400, ("add: EMCP method %s is NOT on_stack " INTPTR_FORMAT,
3835                               old_method->name_and_sig_as_C_string(), old_method));
3836       }
3837     }
3838   }
3839 
3840   // Add previous version if any methods are still running.
3841   RC_TRACE(0x00000400, ("add: scratch class added; one of its methods is on_stack"));
3842   assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");
3843   scratch_class->link_previous_versions(previous_versions());
3844   link_previous_versions(scratch_class());
3845 } // end add_previous_version()
3846 
3847 Method* InstanceKlass::method_with_idnum(int idnum) {
3848   Method* m = NULL;
3849   if (idnum < methods()->length()) {
3850     m = methods()->at(idnum);
3851   }
3852   if (m == NULL || m->method_idnum() != idnum) {
3853     for (int index = 0; index < methods()->length(); ++index) {
3854       m = methods()->at(index);
3855       if (m->method_idnum() == idnum) {
3856         return m;
3857       }
3858     }
3859     // None found, return null for the caller to handle.
3860     return NULL;
3861   }
3862   return m;
3863 }
3864 
3865 
3866 Method* InstanceKlass::method_with_orig_idnum(int idnum) {
3867   if (idnum >= methods()->length()) {
3868     return NULL;
3869   }
3870   Method* m = methods()->at(idnum);
3871   if (m != NULL && m->orig_method_idnum() == idnum) {
3872     return m;
3873   }
3874   // Obsolete method idnum does not match the original idnum
3875   for (int index = 0; index < methods()->length(); ++index) {
3876     m = methods()->at(index);
3877     if (m->orig_method_idnum() == idnum) {
3878       return m;
3879     }
3880   }
3881   // None found, return null for the caller to handle.
3882   return NULL;
3883 }
3884 
3885 
3886 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {
3887   InstanceKlass* holder = get_klass_version(version);
3888   if (holder == NULL) {
3889     return NULL; // The version of klass is gone, no method is found
3890   }
3891   Method* method = holder->method_with_orig_idnum(idnum);
3892   return method;
3893 }
3894 
3895 
3896 jint InstanceKlass::get_cached_class_file_len() {
3897   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
3898 }
3899 
3900 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
3901   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
3902 }