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