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