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