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