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