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