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