1 /*
   2  * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/javaClasses.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "classfile/verifier.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "compiler/compileBroker.hpp"
  31 #include "gc/shared/collectedHeap.inline.hpp"
  32 #include "gc/shared/specialized_oop_closures.hpp"
  33 #include "interpreter/oopMapCache.hpp"
  34 #include "interpreter/rewriter.hpp"
  35 #include "jvmtifiles/jvmti.h"
  36 #include "memory/heapInspection.hpp"
  37 #include "memory/iterator.inline.hpp"
  38 #include "memory/metadataFactory.hpp"
  39 #include "memory/oopFactory.hpp"
  40 #include "oops/fieldStreams.hpp"
  41 #include "oops/instanceClassLoaderKlass.hpp"
  42 #include "oops/instanceKlass.inline.hpp"
  43 #include "oops/instanceMirrorKlass.hpp"
  44 #include "oops/instanceOop.hpp"
  45 #include "oops/klass.inline.hpp"
  46 #include "oops/method.hpp"
  47 #include "oops/oop.inline.hpp"
  48 #include "oops/symbol.hpp"
  49 #include "prims/jvmtiExport.hpp"
  50 #include "prims/jvmtiRedefineClasses.hpp"
  51 #include "prims/jvmtiRedefineClassesTrace.hpp"
  52 #include "prims/jvmtiThreadState.hpp"
  53 #include "prims/methodComparator.hpp"
  54 #include "runtime/atomic.inline.hpp"
  55 #include "runtime/fieldDescriptor.hpp"
  56 #include "runtime/handles.inline.hpp"
  57 #include "runtime/javaCalls.hpp"
  58 #include "runtime/mutexLocker.hpp"
  59 #include "runtime/orderAccess.inline.hpp"
  60 #include "runtime/thread.inline.hpp"
  61 #include "services/classLoadingService.hpp"
  62 #include "services/threadService.hpp"
  63 #include "utilities/dtrace.hpp"
  64 #include "utilities/macros.hpp"
  65 #ifdef COMPILER1
  66 #include "c1/c1_Compiler.hpp"
  67 #endif
  68 
  69 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  70 
  71 #ifdef DTRACE_ENABLED
  72 
  73 
  74 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
  75 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
  76 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
  77 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
  78 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
  79 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
  80 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
  81 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
  82 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
  83   {                                                              \
  84     char* data = NULL;                                           \
  85     int len = 0;                                                 \
  86     Symbol* name = (clss)->name();                               \
  87     if (name != NULL) {                                          \
  88       data = (char*)name->bytes();                               \
  89       len = name->utf8_length();                                 \
  90     }                                                            \
  91     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
  92       data, len, (clss)->class_loader(), thread_type);           \
  93   }
  94 
  95 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
  96   {                                                              \
  97     char* data = NULL;                                           \
  98     int len = 0;                                                 \
  99     Symbol* name = (clss)->name();                               \
 100     if (name != NULL) {                                          \
 101       data = (char*)name->bytes();                               \
 102       len = name->utf8_length();                                 \
 103     }                                                            \
 104     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
 105       data, len, (clss)->class_loader(), thread_type, wait);     \
 106   }
 107 
 108 #else //  ndef DTRACE_ENABLED
 109 
 110 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)
 111 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait)
 112 
 113 #endif //  ndef DTRACE_ENABLED
 114 
 115 volatile int InstanceKlass::_total_instanceKlass_count = 0;
 116 
 117 InstanceKlass* InstanceKlass::allocate_instance_klass(
 118                                               ClassLoaderData* loader_data,
 119                                               int vtable_len,
 120                                               int itable_len,
 121                                               int static_field_size,
 122                                               int nonstatic_oop_map_size,
 123                                               ReferenceType rt,
 124                                               AccessFlags access_flags,
 125                                               Symbol* name,
 126                                               Klass* super_klass,
 127                                               bool is_anonymous,
 128                                               TRAPS) {
 129 
 130   int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
 131                                  access_flags.is_interface(), is_anonymous);
 132 
 133   // Allocation
 134   InstanceKlass* ik;
 135   if (rt == REF_NONE) {
 136     if (name == vmSymbols::java_lang_Class()) {
 137       ik = new (loader_data, size, THREAD) InstanceMirrorKlass(
 138         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
 139         access_flags, is_anonymous);
 140     } else if (name == vmSymbols::java_lang_ClassLoader() ||
 141           (SystemDictionary::ClassLoader_klass_loaded() &&
 142           super_klass != NULL &&
 143           super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {
 144       ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(
 145         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
 146         access_flags, is_anonymous);
 147     } else {
 148       // normal class
 149       ik = new (loader_data, size, THREAD) InstanceKlass(
 150         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
 151         access_flags, is_anonymous);
 152     }
 153   } else {
 154     // reference klass
 155     ik = new (loader_data, size, THREAD) InstanceRefKlass(
 156         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
 157         access_flags, is_anonymous);
 158   }
 159 
 160   // Check for pending exception before adding to the loader data and incrementing
 161   // class count.  Can get OOM here.
 162   if (HAS_PENDING_EXCEPTION) {
 163     return NULL;
 164   }
 165 
 166   // Add all classes to our internal class loader list here,
 167   // including classes in the bootstrap (NULL) class loader.
 168   loader_data->add_class(ik);
 169 
 170   Atomic::inc(&_total_instanceKlass_count);
 171   return ik;
 172 }
 173 
 174 
 175 // copy method ordering from resource area to Metaspace
 176 void InstanceKlass::copy_method_ordering(intArray* m, TRAPS) {
 177   if (m != NULL) {
 178     // allocate a new array and copy contents (memcpy?)
 179     _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
 180     for (int i = 0; i < m->length(); i++) {
 181       _method_ordering->at_put(i, m->at(i));
 182     }
 183   } else {
 184     _method_ordering = Universe::the_empty_int_array();
 185   }
 186 }
 187 
 188 // create a new array of vtable_indices for default methods
 189 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
 190   Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
 191   assert(default_vtable_indices() == NULL, "only create once");
 192   set_default_vtable_indices(vtable_indices);
 193   return vtable_indices;
 194 }
 195 
 196 InstanceKlass::InstanceKlass(int vtable_len,
 197                              int itable_len,
 198                              int static_field_size,
 199                              int nonstatic_oop_map_size,
 200                              ReferenceType rt,
 201                              AccessFlags access_flags,
 202                              bool is_anonymous) {
 203   No_Safepoint_Verifier no_safepoint; // until k becomes parsable
 204 
 205   int iksize = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
 206                                    access_flags.is_interface(), is_anonymous);
 207 
 208   set_vtable_length(vtable_len);
 209   set_itable_length(itable_len);
 210   set_static_field_size(static_field_size);
 211   set_nonstatic_oop_map_size(nonstatic_oop_map_size);
 212   set_access_flags(access_flags);
 213   _misc_flags = 0;  // initialize to zero
 214   set_is_anonymous(is_anonymous);
 215   assert(size() == iksize, "wrong size for object");
 216 
 217   set_array_klasses(NULL);
 218   set_methods(NULL);
 219   set_method_ordering(NULL);
 220   set_default_methods(NULL);
 221   set_default_vtable_indices(NULL);
 222   set_local_interfaces(NULL);
 223   set_transitive_interfaces(NULL);
 224   init_implementor();
 225   set_fields(NULL, 0);
 226   set_constants(NULL);
 227   set_class_loader_data(NULL);
 228   set_source_file_name_index(0);
 229   set_source_debug_extension(NULL, 0);
 230   set_array_name(NULL);
 231   set_inner_classes(NULL);
 232   set_static_oop_field_count(0);
 233   set_nonstatic_field_size(0);
 234   set_is_marked_dependent(false);
 235   set_has_unloaded_dependent(false);
 236   set_init_state(InstanceKlass::allocated);
 237   set_init_thread(NULL);
 238   set_reference_type(rt);
 239   set_oop_map_cache(NULL);
 240   set_jni_ids(NULL);
 241   set_osr_nmethods_head(NULL);
 242   set_breakpoints(NULL);
 243   init_previous_versions();
 244   set_generic_signature_index(0);
 245   release_set_methods_jmethod_ids(NULL);
 246   set_annotations(NULL);
 247   set_jvmti_cached_class_field_map(NULL);
 248   set_initial_method_idnum(0);
 249   _dependencies = NULL;
 250   set_jvmti_cached_class_field_map(NULL);
 251   set_cached_class_file(NULL);
 252   set_initial_method_idnum(0);
 253   set_minor_version(0);
 254   set_major_version(0);
 255   NOT_PRODUCT(_verify_count = 0;)
 256 
 257   // initialize the non-header words to zero
 258   intptr_t* p = (intptr_t*)this;
 259   for (int index = InstanceKlass::header_size(); index < iksize; index++) {
 260     p[index] = NULL_WORD;
 261   }
 262 
 263   // Set temporary value until parseClassFile updates it with the real instance
 264   // size.
 265   set_layout_helper(Klass::instance_layout_helper(0, true));
 266 }
 267 
 268 
 269 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
 270                                        Array<Method*>* methods) {
 271   if (methods != NULL && methods != Universe::the_empty_method_array() &&
 272       !methods->is_shared()) {
 273     for (int i = 0; i < methods->length(); i++) {
 274       Method* method = methods->at(i);
 275       if (method == NULL) continue;  // maybe null if error processing
 276       // Only want to delete methods that are not executing for RedefineClasses.
 277       // The previous version will point to them so they're not totally dangling
 278       assert (!method->on_stack(), "shouldn't be called with methods on stack");
 279       MetadataFactory::free_metadata(loader_data, method);
 280     }
 281     MetadataFactory::free_array<Method*>(loader_data, methods);
 282   }
 283 }
 284 
 285 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
 286                                           Klass* super_klass,
 287                                           Array<Klass*>* local_interfaces,
 288                                           Array<Klass*>* transitive_interfaces) {
 289   // Only deallocate transitive interfaces if not empty, same as super class
 290   // or same as local interfaces.  See code in parseClassFile.
 291   Array<Klass*>* ti = transitive_interfaces;
 292   if (ti != Universe::the_empty_klass_array() && ti != local_interfaces) {
 293     // check that the interfaces don't come from super class
 294     Array<Klass*>* sti = (super_klass == NULL) ? NULL :
 295                     InstanceKlass::cast(super_klass)->transitive_interfaces();
 296     if (ti != sti && ti != NULL && !ti->is_shared()) {
 297       MetadataFactory::free_array<Klass*>(loader_data, ti);
 298     }
 299   }
 300 
 301   // local interfaces can be empty
 302   if (local_interfaces != Universe::the_empty_klass_array() &&
 303       local_interfaces != NULL && !local_interfaces->is_shared()) {
 304     MetadataFactory::free_array<Klass*>(loader_data, local_interfaces);
 305   }
 306 }
 307 
 308 // This function deallocates the metadata and C heap pointers that the
 309 // InstanceKlass points to.
 310 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
 311 
 312   // Orphan the mirror first, CMS thinks it's still live.
 313   if (java_mirror() != NULL) {
 314     java_lang_Class::set_klass(java_mirror(), NULL);
 315   }
 316 
 317   // Need to take this class off the class loader data list.
 318   loader_data->remove_class(this);
 319 
 320   // The array_klass for this class is created later, after error handling.
 321   // For class redefinition, we keep the original class so this scratch class
 322   // doesn't have an array class.  Either way, assert that there is nothing
 323   // to deallocate.
 324   assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
 325 
 326   // Release C heap allocated data that this might point to, which includes
 327   // reference counting symbol names.
 328   release_C_heap_structures();
 329 
 330   deallocate_methods(loader_data, methods());
 331   set_methods(NULL);
 332 
 333   if (method_ordering() != NULL &&
 334       method_ordering() != Universe::the_empty_int_array() &&
 335       !method_ordering()->is_shared()) {
 336     MetadataFactory::free_array<int>(loader_data, method_ordering());
 337   }
 338   set_method_ordering(NULL);
 339 
 340   // default methods can be empty
 341   if (default_methods() != NULL &&
 342       default_methods() != Universe::the_empty_method_array() &&
 343       !default_methods()->is_shared()) {
 344     MetadataFactory::free_array<Method*>(loader_data, default_methods());
 345   }
 346   // Do NOT deallocate the default methods, they are owned by superinterfaces.
 347   set_default_methods(NULL);
 348 
 349   // default methods vtable indices can be empty
 350   if (default_vtable_indices() != NULL &&
 351       !default_vtable_indices()->is_shared()) {
 352     MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
 353   }
 354   set_default_vtable_indices(NULL);
 355 
 356 
 357   // This array is in Klass, but remove it with the InstanceKlass since
 358   // this place would be the only caller and it can share memory with transitive
 359   // interfaces.
 360   if (secondary_supers() != NULL &&
 361       secondary_supers() != Universe::the_empty_klass_array() &&
 362       secondary_supers() != transitive_interfaces() &&
 363       !secondary_supers()->is_shared()) {
 364     MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
 365   }
 366   set_secondary_supers(NULL);
 367 
 368   deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
 369   set_transitive_interfaces(NULL);
 370   set_local_interfaces(NULL);
 371 
 372   if (fields() != NULL && !fields()->is_shared()) {
 373     MetadataFactory::free_array<jushort>(loader_data, fields());
 374   }
 375   set_fields(NULL, 0);
 376 
 377   // If a method from a redefined class is using this constant pool, don't
 378   // delete it, yet.  The new class's previous version will point to this.
 379   if (constants() != NULL) {
 380     assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
 381     if (!constants()->is_shared()) {
 382       MetadataFactory::free_metadata(loader_data, constants());
 383     }
 384     set_constants(NULL);
 385   }
 386 
 387   if (inner_classes() != NULL &&
 388       inner_classes() != Universe::the_empty_short_array() &&
 389       !inner_classes()->is_shared()) {
 390     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
 391   }
 392   set_inner_classes(NULL);
 393 
 394   // We should deallocate the Annotations instance if it's not in shared spaces.
 395   if (annotations() != NULL && !annotations()->is_shared()) {
 396     MetadataFactory::free_metadata(loader_data, annotations());
 397   }
 398   set_annotations(NULL);
 399 }
 400 
 401 bool InstanceKlass::should_be_initialized() const {
 402   return !is_initialized();
 403 }
 404 
 405 klassVtable* InstanceKlass::vtable() const {
 406   return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());
 407 }
 408 
 409 klassItable* InstanceKlass::itable() const {
 410   return new klassItable(instanceKlassHandle(this));
 411 }
 412 
 413 void InstanceKlass::eager_initialize(Thread *thread) {
 414   if (!EagerInitialization) return;
 415 
 416   if (this->is_not_initialized()) {
 417     // abort if the the class has a class initializer
 418     if (this->class_initializer() != NULL) return;
 419 
 420     // abort if it is java.lang.Object (initialization is handled in genesis)
 421     Klass* super = this->super();
 422     if (super == NULL) return;
 423 
 424     // abort if the super class should be initialized
 425     if (!InstanceKlass::cast(super)->is_initialized()) return;
 426 
 427     // call body to expose the this pointer
 428     instanceKlassHandle this_k(thread, this);
 429     eager_initialize_impl(this_k);
 430   }
 431 }
 432 
 433 // JVMTI spec thinks there are signers and protection domain in the
 434 // instanceKlass.  These accessors pretend these fields are there.
 435 // The hprof specification also thinks these fields are in InstanceKlass.
 436 oop InstanceKlass::protection_domain() const {
 437   // return the protection_domain from the mirror
 438   return java_lang_Class::protection_domain(java_mirror());
 439 }
 440 
 441 // To remove these from requires an incompatible change and CCC request.
 442 objArrayOop InstanceKlass::signers() const {
 443   // return the signers from the mirror
 444   return java_lang_Class::signers(java_mirror());
 445 }
 446 
 447 oop InstanceKlass::init_lock() const {
 448   // return the init lock from the mirror
 449   oop lock = java_lang_Class::init_lock(java_mirror());
 450   // Prevent reordering with any access of initialization state
 451   OrderAccess::loadload();
 452   assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state
 453          "only fully initialized state can have a null lock");
 454   return lock;
 455 }
 456 
 457 // Set the initialization lock to null so the object can be GC'ed.  Any racing
 458 // threads to get this lock will see a null lock and will not lock.
 459 // That's okay because they all check for initialized state after getting
 460 // the lock and return.
 461 void InstanceKlass::fence_and_clear_init_lock() {
 462   // make sure previous stores are all done, notably the init_state.
 463   OrderAccess::storestore();
 464   java_lang_Class::set_init_lock(java_mirror(), NULL);
 465   assert(!is_not_initialized(), "class must be initialized now");
 466 }
 467 
 468 void InstanceKlass::eager_initialize_impl(instanceKlassHandle this_k) {
 469   EXCEPTION_MARK;
 470   oop init_lock = this_k->init_lock();
 471   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
 472 
 473   // abort if someone beat us to the initialization
 474   if (!this_k->is_not_initialized()) return;  // note: not equivalent to is_initialized()
 475 
 476   ClassState old_state = this_k->init_state();
 477   link_class_impl(this_k, true, THREAD);
 478   if (HAS_PENDING_EXCEPTION) {
 479     CLEAR_PENDING_EXCEPTION;
 480     // Abort if linking the class throws an exception.
 481 
 482     // Use a test to avoid redundantly resetting the state if there's
 483     // no change.  Set_init_state() asserts that state changes make
 484     // progress, whereas here we might just be spinning in place.
 485     if( old_state != this_k->_init_state )
 486       this_k->set_init_state (old_state);
 487   } else {
 488     // linking successfull, mark class as initialized
 489     this_k->set_init_state (fully_initialized);
 490     this_k->fence_and_clear_init_lock();
 491     // trace
 492     if (TraceClassInitialization) {
 493       ResourceMark rm(THREAD);
 494       tty->print_cr("[Initialized %s without side effects]", this_k->external_name());
 495     }
 496   }
 497 }
 498 
 499 
 500 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
 501 // process. The step comments refers to the procedure described in that section.
 502 // Note: implementation moved to static method to expose the this pointer.
 503 void InstanceKlass::initialize(TRAPS) {
 504   if (this->should_be_initialized()) {
 505     HandleMark hm(THREAD);
 506     instanceKlassHandle this_k(THREAD, this);
 507     initialize_impl(this_k, CHECK);
 508     // Note: at this point the class may be initialized
 509     //       OR it may be in the state of being initialized
 510     //       in case of recursive initialization!
 511   } else {
 512     assert(is_initialized(), "sanity check");
 513   }
 514 }
 515 
 516 
 517 bool InstanceKlass::verify_code(
 518     instanceKlassHandle this_k, bool throw_verifyerror, TRAPS) {
 519   // 1) Verify the bytecodes
 520   Verifier::Mode mode =
 521     throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
 522   return Verifier::verify(this_k, mode, this_k->should_verify_class(), THREAD);
 523 }
 524 
 525 
 526 // Used exclusively by the shared spaces dump mechanism to prevent
 527 // classes mapped into the shared regions in new VMs from appearing linked.
 528 
 529 void InstanceKlass::unlink_class() {
 530   assert(is_linked(), "must be linked");
 531   _init_state = loaded;
 532 }
 533 
 534 void InstanceKlass::link_class(TRAPS) {
 535   assert(is_loaded(), "must be loaded");
 536   if (!is_linked()) {
 537     HandleMark hm(THREAD);
 538     instanceKlassHandle this_k(THREAD, this);
 539     link_class_impl(this_k, true, CHECK);
 540   }
 541 }
 542 
 543 // Called to verify that a class can link during initialization, without
 544 // throwing a VerifyError.
 545 bool InstanceKlass::link_class_or_fail(TRAPS) {
 546   assert(is_loaded(), "must be loaded");
 547   if (!is_linked()) {
 548     HandleMark hm(THREAD);
 549     instanceKlassHandle this_k(THREAD, this);
 550     link_class_impl(this_k, false, CHECK_false);
 551   }
 552   return is_linked();
 553 }
 554 
 555 bool InstanceKlass::link_class_impl(
 556     instanceKlassHandle this_k, bool throw_verifyerror, TRAPS) {
 557   // check for error state
 558   if (this_k->is_in_error_state()) {
 559     ResourceMark rm(THREAD);
 560     THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
 561                this_k->external_name(), false);
 562   }
 563   // return if already verified
 564   if (this_k->is_linked()) {
 565     return true;
 566   }
 567 
 568   // Timing
 569   // timer handles recursion
 570   assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
 571   JavaThread* jt = (JavaThread*)THREAD;
 572 
 573   // link super class before linking this class
 574   instanceKlassHandle super(THREAD, this_k->super());
 575   if (super.not_null()) {
 576     if (super->is_interface()) {  // check if super class is an interface
 577       ResourceMark rm(THREAD);
 578       Exceptions::fthrow(
 579         THREAD_AND_LOCATION,
 580         vmSymbols::java_lang_IncompatibleClassChangeError(),
 581         "class %s has interface %s as super class",
 582         this_k->external_name(),
 583         super->external_name()
 584       );
 585       return false;
 586     }
 587 
 588     link_class_impl(super, throw_verifyerror, CHECK_false);
 589   }
 590 
 591   // link all interfaces implemented by this class before linking this class
 592   Array<Klass*>* interfaces = this_k->local_interfaces();
 593   int num_interfaces = interfaces->length();
 594   for (int index = 0; index < num_interfaces; index++) {
 595     HandleMark hm(THREAD);
 596     instanceKlassHandle ih(THREAD, interfaces->at(index));
 597     link_class_impl(ih, throw_verifyerror, CHECK_false);
 598   }
 599 
 600   // in case the class is linked in the process of linking its superclasses
 601   if (this_k->is_linked()) {
 602     return true;
 603   }
 604 
 605   // trace only the link time for this klass that includes
 606   // the verification time
 607   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
 608                              ClassLoader::perf_class_link_selftime(),
 609                              ClassLoader::perf_classes_linked(),
 610                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 611                              jt->get_thread_stat()->perf_timers_addr(),
 612                              PerfClassTraceTime::CLASS_LINK);
 613 
 614   // verification & rewriting
 615   {
 616     oop init_lock = this_k->init_lock();
 617     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
 618     // rewritten will have been set if loader constraint error found
 619     // on an earlier link attempt
 620     // don't verify or rewrite if already rewritten
 621 
 622     if (!this_k->is_linked()) {
 623       if (!this_k->is_rewritten()) {
 624         {
 625           bool verify_ok = verify_code(this_k, throw_verifyerror, THREAD);
 626           if (!verify_ok) {
 627             return false;
 628           }
 629         }
 630 
 631         // Just in case a side-effect of verify linked this class already
 632         // (which can sometimes happen since the verifier loads classes
 633         // using custom class loaders, which are free to initialize things)
 634         if (this_k->is_linked()) {
 635           return true;
 636         }
 637 
 638         // also sets rewritten
 639         this_k->rewrite_class(CHECK_false);
 640       }
 641 
 642       // relocate jsrs and link methods after they are all rewritten
 643       this_k->link_methods(CHECK_false);
 644 
 645       // Initialize the vtable and interface table after
 646       // methods have been rewritten since rewrite may
 647       // fabricate new Method*s.
 648       // also does loader constraint checking
 649       if (!this_k()->is_shared()) {
 650         ResourceMark rm(THREAD);
 651         this_k->vtable()->initialize_vtable(true, CHECK_false);
 652         this_k->itable()->initialize_itable(true, CHECK_false);
 653       }
 654 #ifdef ASSERT
 655       else {
 656         ResourceMark rm(THREAD);
 657         this_k->vtable()->verify(tty, true);
 658         // In case itable verification is ever added.
 659         // this_k->itable()->verify(tty, true);
 660       }
 661 #endif
 662       this_k->set_init_state(linked);
 663       if (JvmtiExport::should_post_class_prepare()) {
 664         Thread *thread = THREAD;
 665         assert(thread->is_Java_thread(), "thread->is_Java_thread()");
 666         JvmtiExport::post_class_prepare((JavaThread *) thread, this_k());
 667       }
 668     }
 669   }
 670   return true;
 671 }
 672 
 673 
 674 // Rewrite the byte codes of all of the methods of a class.
 675 // The rewriter must be called exactly once. Rewriting must happen after
 676 // verification but before the first method of the class is executed.
 677 void InstanceKlass::rewrite_class(TRAPS) {
 678   assert(is_loaded(), "must be loaded");
 679   instanceKlassHandle this_k(THREAD, this);
 680   if (this_k->is_rewritten()) {
 681     assert(this_k()->is_shared(), "rewriting an unshared class?");
 682     return;
 683   }
 684   Rewriter::rewrite(this_k, CHECK);
 685   this_k->set_rewritten();
 686 }
 687 
 688 // Now relocate and link method entry points after class is rewritten.
 689 // This is outside is_rewritten flag. In case of an exception, it can be
 690 // executed more than once.
 691 void InstanceKlass::link_methods(TRAPS) {
 692   int len = methods()->length();
 693   for (int i = len-1; i >= 0; i--) {
 694     methodHandle m(THREAD, methods()->at(i));
 695 
 696     // Set up method entry points for compiler and interpreter    .
 697     m->link_method(m, CHECK);
 698   }
 699 }
 700 
 701 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
 702 void InstanceKlass::initialize_super_interfaces(instanceKlassHandle this_k, TRAPS) {
 703   if (this_k->has_default_methods()) {
 704     for (int i = 0; i < this_k->local_interfaces()->length(); ++i) {
 705       Klass* iface = this_k->local_interfaces()->at(i);
 706       InstanceKlass* ik = InstanceKlass::cast(iface);
 707       if (ik->should_be_initialized()) {
 708         if (ik->has_default_methods()) {
 709           ik->initialize_super_interfaces(ik, THREAD);
 710         }
 711         // Only initialize() interfaces that "declare" concrete methods.
 712         // has_default_methods drives searching superinterfaces since it
 713         // means has_default_methods in its superinterface hierarchy
 714         if (!HAS_PENDING_EXCEPTION && ik->declares_default_methods()) {
 715           ik->initialize(THREAD);
 716         }
 717         if (HAS_PENDING_EXCEPTION) {
 718           Handle e(THREAD, PENDING_EXCEPTION);
 719           CLEAR_PENDING_EXCEPTION;
 720           {
 721             EXCEPTION_MARK;
 722             // Locks object, set state, and notify all waiting threads
 723             this_k->set_initialization_state_and_notify(
 724                 initialization_error, THREAD);
 725 
 726             // ignore any exception thrown, superclass initialization error is
 727             // thrown below
 728             CLEAR_PENDING_EXCEPTION;
 729           }
 730           THROW_OOP(e());
 731         }
 732       }
 733     }
 734   }
 735 }
 736 
 737 void InstanceKlass::initialize_impl(instanceKlassHandle this_k, TRAPS) {
 738   // Make sure klass is linked (verified) before initialization
 739   // A class could already be verified, since it has been reflected upon.
 740   this_k->link_class(CHECK);
 741 
 742   DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_k()), -1);
 743 
 744   bool wait = false;
 745 
 746   // refer to the JVM book page 47 for description of steps
 747   // Step 1
 748   {
 749     oop init_lock = this_k->init_lock();
 750     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
 751 
 752     Thread *self = THREAD; // it's passed the current thread
 753 
 754     // Step 2
 755     // If we were to use wait() instead of waitInterruptibly() then
 756     // we might end up throwing IE from link/symbol resolution sites
 757     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
 758     while(this_k->is_being_initialized() && !this_k->is_reentrant_initialization(self)) {
 759         wait = true;
 760       ol.waitUninterruptibly(CHECK);
 761     }
 762 
 763     // Step 3
 764     if (this_k->is_being_initialized() && this_k->is_reentrant_initialization(self)) {
 765       DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_k()), -1,wait);
 766       return;
 767     }
 768 
 769     // Step 4
 770     if (this_k->is_initialized()) {
 771       DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_k()), -1,wait);
 772       return;
 773     }
 774 
 775     // Step 5
 776     if (this_k->is_in_error_state()) {
 777       DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_k()), -1,wait);
 778       ResourceMark rm(THREAD);
 779       const char* desc = "Could not initialize class ";
 780       const char* className = this_k->external_name();
 781       size_t msglen = strlen(desc) + strlen(className) + 1;
 782       char* message = NEW_RESOURCE_ARRAY(char, msglen);
 783       if (NULL == message) {
 784         // Out of memory: can't create detailed error message
 785         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
 786       } else {
 787         jio_snprintf(message, msglen, "%s%s", desc, className);
 788         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
 789       }
 790     }
 791 
 792     // Step 6
 793     this_k->set_init_state(being_initialized);
 794     this_k->set_init_thread(self);
 795   }
 796 
 797   // Step 7
 798   Klass* super_klass = this_k->super();
 799   if (super_klass != NULL && !this_k->is_interface() && super_klass->should_be_initialized()) {
 800     super_klass->initialize(THREAD);
 801 
 802     if (HAS_PENDING_EXCEPTION) {
 803       Handle e(THREAD, PENDING_EXCEPTION);
 804       CLEAR_PENDING_EXCEPTION;
 805       {
 806         EXCEPTION_MARK;
 807         this_k->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
 808         CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, superclass initialization error is thrown below
 809       }
 810       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_k()), -1,wait);
 811       THROW_OOP(e());
 812     }
 813   }
 814 
 815   // Recursively initialize any superinterfaces that declare default methods
 816   // Only need to recurse if has_default_methods which includes declaring and
 817   // inheriting default methods
 818   if (this_k->has_default_methods()) {
 819     this_k->initialize_super_interfaces(this_k, CHECK);
 820   }
 821 
 822   // Step 8
 823   {
 824     assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
 825     JavaThread* jt = (JavaThread*)THREAD;
 826     DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_k()), -1,wait);
 827     // Timer includes any side effects of class initialization (resolution,
 828     // etc), but not recursive entry into call_class_initializer().
 829     PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
 830                              ClassLoader::perf_class_init_selftime(),
 831                              ClassLoader::perf_classes_inited(),
 832                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 833                              jt->get_thread_stat()->perf_timers_addr(),
 834                              PerfClassTraceTime::CLASS_CLINIT);
 835     this_k->call_class_initializer(THREAD);
 836   }
 837 
 838   // Step 9
 839   if (!HAS_PENDING_EXCEPTION) {
 840     this_k->set_initialization_state_and_notify(fully_initialized, CHECK);
 841     { ResourceMark rm(THREAD);
 842       debug_only(this_k->vtable()->verify(tty, true);)
 843     }
 844   }
 845   else {
 846     // Step 10 and 11
 847     Handle e(THREAD, PENDING_EXCEPTION);
 848     CLEAR_PENDING_EXCEPTION;
 849     // JVMTI has already reported the pending exception
 850     // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
 851     JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
 852     {
 853       EXCEPTION_MARK;
 854       this_k->set_initialization_state_and_notify(initialization_error, THREAD);
 855       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
 856       // JVMTI has already reported the pending exception
 857       // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
 858       JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
 859     }
 860     DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_k()), -1,wait);
 861     if (e->is_a(SystemDictionary::Error_klass())) {
 862       THROW_OOP(e());
 863     } else {
 864       JavaCallArguments args(e);
 865       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
 866                 vmSymbols::throwable_void_signature(),
 867                 &args);
 868     }
 869   }
 870   DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_k()), -1,wait);
 871 }
 872 
 873 
 874 // Note: implementation moved to static method to expose the this pointer.
 875 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
 876   instanceKlassHandle kh(THREAD, this);
 877   set_initialization_state_and_notify_impl(kh, state, CHECK);
 878 }
 879 
 880 void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_k, ClassState state, TRAPS) {
 881   oop init_lock = this_k->init_lock();
 882   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
 883   this_k->set_init_state(state);
 884   this_k->fence_and_clear_init_lock();
 885   ol.notify_all(CHECK);
 886 }
 887 
 888 // The embedded _implementor field can only record one implementor.
 889 // When there are more than one implementors, the _implementor field
 890 // is set to the interface Klass* itself. Following are the possible
 891 // values for the _implementor field:
 892 //   NULL                  - no implementor
 893 //   implementor Klass*    - one implementor
 894 //   self                  - more than one implementor
 895 //
 896 // The _implementor field only exists for interfaces.
 897 void InstanceKlass::add_implementor(Klass* k) {
 898   assert(Compile_lock->owned_by_self(), "");
 899   assert(is_interface(), "not interface");
 900   // Filter out my subinterfaces.
 901   // (Note: Interfaces are never on the subklass list.)
 902   if (InstanceKlass::cast(k)->is_interface()) return;
 903 
 904   // Filter out subclasses whose supers already implement me.
 905   // (Note: CHA must walk subclasses of direct implementors
 906   // in order to locate indirect implementors.)
 907   Klass* sk = InstanceKlass::cast(k)->super();
 908   if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
 909     // We only need to check one immediate superclass, since the
 910     // implements_interface query looks at transitive_interfaces.
 911     // Any supers of the super have the same (or fewer) transitive_interfaces.
 912     return;
 913 
 914   Klass* ik = implementor();
 915   if (ik == NULL) {
 916     set_implementor(k);
 917   } else if (ik != this) {
 918     // There is already an implementor. Use itself as an indicator of
 919     // more than one implementors.
 920     set_implementor(this);
 921   }
 922 
 923   // The implementor also implements the transitive_interfaces
 924   for (int index = 0; index < local_interfaces()->length(); index++) {
 925     InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
 926   }
 927 }
 928 
 929 void InstanceKlass::init_implementor() {
 930   if (is_interface()) {
 931     set_implementor(NULL);
 932   }
 933 }
 934 
 935 
 936 void InstanceKlass::process_interfaces(Thread *thread) {
 937   // link this class into the implementors list of every interface it implements
 938   for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
 939     assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
 940     InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
 941     assert(interf->is_interface(), "expected interface");
 942     interf->add_implementor(this);
 943   }
 944 }
 945 
 946 bool InstanceKlass::can_be_primary_super_slow() const {
 947   if (is_interface())
 948     return false;
 949   else
 950     return Klass::can_be_primary_super_slow();
 951 }
 952 
 953 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {
 954   // The secondaries are the implemented interfaces.
 955   InstanceKlass* ik = InstanceKlass::cast(this);
 956   Array<Klass*>* interfaces = ik->transitive_interfaces();
 957   int num_secondaries = num_extra_slots + interfaces->length();
 958   if (num_secondaries == 0) {
 959     // Must share this for correct bootstrapping!
 960     set_secondary_supers(Universe::the_empty_klass_array());
 961     return NULL;
 962   } else if (num_extra_slots == 0) {
 963     // The secondary super list is exactly the same as the transitive interfaces.
 964     // Redefine classes has to be careful not to delete this!
 965     set_secondary_supers(interfaces);
 966     return NULL;
 967   } else {
 968     // Copy transitive interfaces to a temporary growable array to be constructed
 969     // into the secondary super list with extra slots.
 970     GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
 971     for (int i = 0; i < interfaces->length(); i++) {
 972       secondaries->push(interfaces->at(i));
 973     }
 974     return secondaries;
 975   }
 976 }
 977 
 978 bool InstanceKlass::compute_is_subtype_of(Klass* k) {
 979   if (k->is_interface()) {
 980     return implements_interface(k);
 981   } else {
 982     return Klass::compute_is_subtype_of(k);
 983   }
 984 }
 985 
 986 bool InstanceKlass::implements_interface(Klass* k) const {
 987   if (this == k) return true;
 988   assert(k->is_interface(), "should be an interface class");
 989   for (int i = 0; i < transitive_interfaces()->length(); i++) {
 990     if (transitive_interfaces()->at(i) == k) {
 991       return true;
 992     }
 993   }
 994   return false;
 995 }
 996 
 997 bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
 998   // Verify direct super interface
 999   if (this == k) return true;
1000   assert(k->is_interface(), "should be an interface class");
1001   for (int i = 0; i < local_interfaces()->length(); i++) {
1002     if (local_interfaces()->at(i) == k) {
1003       return true;
1004     }
1005   }
1006   return false;
1007 }
1008 
1009 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
1010   if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
1011   if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
1012     report_java_out_of_memory("Requested array size exceeds VM limit");
1013     JvmtiExport::post_array_size_exhausted();
1014     THROW_OOP_0(Universe::out_of_memory_error_array_size());
1015   }
1016   int size = objArrayOopDesc::object_size(length);
1017   Klass* ak = array_klass(n, CHECK_NULL);
1018   KlassHandle h_ak (THREAD, ak);
1019   objArrayOop o =
1020     (objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);
1021   return o;
1022 }
1023 
1024 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
1025   if (TraceFinalizerRegistration) {
1026     tty->print("Registered ");
1027     i->print_value_on(tty);
1028     tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);
1029   }
1030   instanceHandle h_i(THREAD, i);
1031   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1032   JavaValue result(T_VOID);
1033   JavaCallArguments args(h_i);
1034   methodHandle mh (THREAD, Universe::finalizer_register_method());
1035   JavaCalls::call(&result, mh, &args, CHECK_NULL);
1036   return h_i();
1037 }
1038 
1039 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1040   bool has_finalizer_flag = has_finalizer(); // Query before possible GC
1041   int size = size_helper();  // Query before forming handle.
1042 
1043   KlassHandle h_k(THREAD, this);
1044 
1045   instanceOop i;
1046 
1047   i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);
1048   if (has_finalizer_flag && !RegisterFinalizersAtInit) {
1049     i = register_finalizer(i, CHECK_NULL);
1050   }
1051   return i;
1052 }
1053 
1054 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1055   if (is_interface() || is_abstract()) {
1056     ResourceMark rm(THREAD);
1057     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1058               : vmSymbols::java_lang_InstantiationException(), external_name());
1059   }
1060   if (this == SystemDictionary::Class_klass()) {
1061     ResourceMark rm(THREAD);
1062     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1063               : vmSymbols::java_lang_IllegalAccessException(), external_name());
1064   }
1065 }
1066 
1067 Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
1068   instanceKlassHandle this_k(THREAD, this);
1069   return array_klass_impl(this_k, or_null, n, THREAD);
1070 }
1071 
1072 Klass* InstanceKlass::array_klass_impl(instanceKlassHandle this_k, bool or_null, int n, TRAPS) {
1073   if (this_k->array_klasses() == NULL) {
1074     if (or_null) return NULL;
1075 
1076     ResourceMark rm;
1077     JavaThread *jt = (JavaThread *)THREAD;
1078     {
1079       // Atomic creation of array_klasses
1080       MutexLocker mc(Compile_lock, THREAD);   // for vtables
1081       MutexLocker ma(MultiArray_lock, THREAD);
1082 
1083       // Check if update has already taken place
1084       if (this_k->array_klasses() == NULL) {
1085         Klass*    k = ObjArrayKlass::allocate_objArray_klass(this_k->class_loader_data(), 1, this_k, CHECK_NULL);
1086         this_k->set_array_klasses(k);
1087       }
1088     }
1089   }
1090   // _this will always be set at this point
1091   ObjArrayKlass* oak = (ObjArrayKlass*)this_k->array_klasses();
1092   if (or_null) {
1093     return oak->array_klass_or_null(n);
1094   }
1095   return oak->array_klass(n, THREAD);
1096 }
1097 
1098 Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
1099   return array_klass_impl(or_null, 1, THREAD);
1100 }
1101 
1102 void InstanceKlass::call_class_initializer(TRAPS) {
1103   instanceKlassHandle ik (THREAD, this);
1104   call_class_initializer_impl(ik, THREAD);
1105 }
1106 
1107 static int call_class_initializer_impl_counter = 0;   // for debugging
1108 
1109 Method* InstanceKlass::class_initializer() {
1110   Method* clinit = find_method(
1111       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1112   if (clinit != NULL && clinit->has_valid_initializer_flags()) {
1113     return clinit;
1114   }
1115   return NULL;
1116 }
1117 
1118 void InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_k, TRAPS) {
1119   if (ReplayCompiles &&
1120       (ReplaySuppressInitializers == 1 ||
1121        ReplaySuppressInitializers >= 2 && this_k->class_loader() != NULL)) {
1122     // Hide the existence of the initializer for the purpose of replaying the compile
1123     return;
1124   }
1125 
1126   methodHandle h_method(THREAD, this_k->class_initializer());
1127   assert(!this_k->is_initialized(), "we cannot initialize twice");
1128   if (TraceClassInitialization) {
1129     tty->print("%d Initializing ", call_class_initializer_impl_counter++);
1130     this_k->name()->print_value();
1131     tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", (address)this_k());
1132   }
1133   if (h_method() != NULL) {
1134     JavaCallArguments args; // No arguments
1135     JavaValue result(T_VOID);
1136     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1137   }
1138 }
1139 
1140 
1141 void InstanceKlass::mask_for(methodHandle method, int bci,
1142   InterpreterOopMap* entry_for) {
1143   // Dirty read, then double-check under a lock.
1144   if (_oop_map_cache == NULL) {
1145     // Otherwise, allocate a new one.
1146     MutexLocker x(OopMapCacheAlloc_lock);
1147     // First time use. Allocate a cache in C heap
1148     if (_oop_map_cache == NULL) {
1149       // Release stores from OopMapCache constructor before assignment
1150       // to _oop_map_cache. C++ compilers on ppc do not emit the
1151       // required memory barrier only because of the volatile
1152       // qualifier of _oop_map_cache.
1153       OrderAccess::release_store_ptr(&_oop_map_cache, new OopMapCache());
1154     }
1155   }
1156   // _oop_map_cache is constant after init; lookup below does is own locking.
1157   _oop_map_cache->lookup(method, bci, entry_for);
1158 }
1159 
1160 
1161 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1162   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1163     Symbol* f_name = fs.name();
1164     Symbol* f_sig  = fs.signature();
1165     if (f_name == name && f_sig == sig) {
1166       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1167       return true;
1168     }
1169   }
1170   return false;
1171 }
1172 
1173 
1174 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1175   const int n = local_interfaces()->length();
1176   for (int i = 0; i < n; i++) {
1177     Klass* intf1 = local_interfaces()->at(i);
1178     assert(intf1->is_interface(), "just checking type");
1179     // search for field in current interface
1180     if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
1181       assert(fd->is_static(), "interface field must be static");
1182       return intf1;
1183     }
1184     // search for field in direct superinterfaces
1185     Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
1186     if (intf2 != NULL) return intf2;
1187   }
1188   // otherwise field lookup fails
1189   return NULL;
1190 }
1191 
1192 
1193 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1194   // search order according to newest JVM spec (5.4.3.2, p.167).
1195   // 1) search for field in current klass
1196   if (find_local_field(name, sig, fd)) {
1197     return const_cast<InstanceKlass*>(this);
1198   }
1199   // 2) search for field recursively in direct superinterfaces
1200   { Klass* intf = find_interface_field(name, sig, fd);
1201     if (intf != NULL) return intf;
1202   }
1203   // 3) apply field lookup recursively if superclass exists
1204   { Klass* supr = super();
1205     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
1206   }
1207   // 4) otherwise field lookup fails
1208   return NULL;
1209 }
1210 
1211 
1212 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1213   // search order according to newest JVM spec (5.4.3.2, p.167).
1214   // 1) search for field in current klass
1215   if (find_local_field(name, sig, fd)) {
1216     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1217   }
1218   // 2) search for field recursively in direct superinterfaces
1219   if (is_static) {
1220     Klass* intf = find_interface_field(name, sig, fd);
1221     if (intf != NULL) return intf;
1222   }
1223   // 3) apply field lookup recursively if superclass exists
1224   { Klass* supr = super();
1225     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
1226   }
1227   // 4) otherwise field lookup fails
1228   return NULL;
1229 }
1230 
1231 
1232 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1233   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1234     if (fs.offset() == offset) {
1235       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1236       if (fd->is_static() == is_static) return true;
1237     }
1238   }
1239   return false;
1240 }
1241 
1242 
1243 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1244   Klass* klass = const_cast<InstanceKlass*>(this);
1245   while (klass != NULL) {
1246     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
1247       return true;
1248     }
1249     klass = klass->super();
1250   }
1251   return false;
1252 }
1253 
1254 
1255 void InstanceKlass::methods_do(void f(Method* method)) {
1256   // Methods aren't stable until they are loaded.  This can be read outside
1257   // a lock through the ClassLoaderData for profiling
1258   if (!is_loaded()) {
1259     return;
1260   }
1261 
1262   int len = methods()->length();
1263   for (int index = 0; index < len; index++) {
1264     Method* m = methods()->at(index);
1265     assert(m->is_method(), "must be method");
1266     f(m);
1267   }
1268 }
1269 
1270 
1271 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
1272   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1273     if (fs.access_flags().is_static()) {
1274       fieldDescriptor& fd = fs.field_descriptor();
1275       cl->do_field(&fd);
1276     }
1277   }
1278 }
1279 
1280 
1281 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
1282   instanceKlassHandle h_this(THREAD, this);
1283   do_local_static_fields_impl(h_this, f, mirror, CHECK);
1284 }
1285 
1286 
1287 void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_k,
1288                              void f(fieldDescriptor* fd, Handle, TRAPS), Handle mirror, TRAPS) {
1289   for (JavaFieldStream fs(this_k()); !fs.done(); fs.next()) {
1290     if (fs.access_flags().is_static()) {
1291       fieldDescriptor& fd = fs.field_descriptor();
1292       f(&fd, mirror, CHECK);
1293     }
1294   }
1295 }
1296 
1297 
1298 static int compare_fields_by_offset(int* a, int* b) {
1299   return a[0] - b[0];
1300 }
1301 
1302 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
1303   InstanceKlass* super = superklass();
1304   if (super != NULL) {
1305     super->do_nonstatic_fields(cl);
1306   }
1307   fieldDescriptor fd;
1308   int length = java_fields_count();
1309   // In DebugInfo nonstatic fields are sorted by offset.
1310   int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
1311   int j = 0;
1312   for (int i = 0; i < length; i += 1) {
1313     fd.reinitialize(this, i);
1314     if (!fd.is_static()) {
1315       fields_sorted[j + 0] = fd.offset();
1316       fields_sorted[j + 1] = i;
1317       j += 2;
1318     }
1319   }
1320   if (j > 0) {
1321     length = j;
1322     // _sort_Fn is defined in growableArray.hpp.
1323     qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
1324     for (int i = 0; i < length; i += 2) {
1325       fd.reinitialize(this, fields_sorted[i + 1]);
1326       assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
1327       cl->do_field(&fd);
1328     }
1329   }
1330   FREE_C_HEAP_ARRAY(int, fields_sorted);
1331 }
1332 
1333 
1334 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
1335   if (array_klasses() != NULL)
1336     ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
1337 }
1338 
1339 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
1340   if (array_klasses() != NULL)
1341     ArrayKlass::cast(array_klasses())->array_klasses_do(f);
1342 }
1343 
1344 #ifdef ASSERT
1345 static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {
1346   int len = methods->length();
1347   for (int index = 0; index < len; index++) {
1348     Method* m = methods->at(index);
1349     assert(m->is_method(), "must be method");
1350     if (m->signature() == signature && m->name() == name) {
1351        return index;
1352     }
1353   }
1354   return -1;
1355 }
1356 #endif
1357 
1358 static int binary_search(Array<Method*>* methods, Symbol* name) {
1359   int len = methods->length();
1360   // methods are sorted, so do binary search
1361   int l = 0;
1362   int h = len - 1;
1363   while (l <= h) {
1364     int mid = (l + h) >> 1;
1365     Method* m = methods->at(mid);
1366     assert(m->is_method(), "must be method");
1367     int res = m->name()->fast_compare(name);
1368     if (res == 0) {
1369       return mid;
1370     } else if (res < 0) {
1371       l = mid + 1;
1372     } else {
1373       h = mid - 1;
1374     }
1375   }
1376   return -1;
1377 }
1378 
1379 // find_method looks up the name/signature in the local methods array
1380 Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {
1381   return find_method_impl(name, signature, find_overpass, find_static);
1382 }
1383 
1384 Method* InstanceKlass::find_method_impl(Symbol* name, Symbol* signature,
1385                                         OverpassLookupMode overpass_mode, StaticLookupMode static_mode) const {
1386   return InstanceKlass::find_method_impl(methods(), name, signature, overpass_mode, static_mode);
1387 }
1388 
1389 // find_instance_method looks up the name/signature in the local methods array
1390 // and skips over static methods
1391 Method* InstanceKlass::find_instance_method(
1392     Array<Method*>* methods, Symbol* name, Symbol* signature) {
1393   Method* meth = InstanceKlass::find_method_impl(methods, name, signature,
1394                                                  find_overpass, skip_static);
1395   assert(((meth == NULL) || !meth->is_static()), "find_instance_method should have skipped statics");
1396   return meth;
1397 }
1398 
1399 // find_instance_method looks up the name/signature in the local methods array
1400 // and skips over static methods
1401 Method* InstanceKlass::find_instance_method(Symbol* name, Symbol* signature) {
1402     return InstanceKlass::find_instance_method(methods(), name, signature);
1403 }
1404 
1405 // find_method looks up the name/signature in the local methods array
1406 Method* InstanceKlass::find_method(
1407     Array<Method*>* methods, Symbol* name, Symbol* signature) {
1408   return InstanceKlass::find_method_impl(methods, name, signature, find_overpass, find_static);
1409 }
1410 
1411 Method* InstanceKlass::find_method_impl(
1412     Array<Method*>* methods, Symbol* name, Symbol* signature, OverpassLookupMode overpass_mode, StaticLookupMode static_mode) {
1413   int hit = find_method_index(methods, name, signature, overpass_mode, static_mode);
1414   return hit >= 0 ? methods->at(hit): NULL;
1415 }
1416 
1417 bool InstanceKlass::method_matches(Method* m, Symbol* signature, bool skipping_overpass, bool skipping_static) {
1418     return (m->signature() == signature) &&
1419             (!skipping_overpass || !m->is_overpass()) &&
1420             (!skipping_static || !m->is_static());
1421 }
1422 
1423 // Used directly for default_methods to find the index into the
1424 // default_vtable_indices, and indirectly by find_method
1425 // find_method_index looks in the local methods array to return the index
1426 // of the matching name/signature. If, overpass methods are being ignored,
1427 // the search continues to find a potential non-overpass match.  This capability
1428 // is important during method resolution to prefer a static method, for example,
1429 // over an overpass method.
1430 int InstanceKlass::find_method_index(
1431     Array<Method*>* methods, Symbol* name, Symbol* signature, OverpassLookupMode overpass_mode, StaticLookupMode static_mode) {
1432   bool skipping_overpass = (overpass_mode == skip_overpass);
1433   bool skipping_static = (static_mode == skip_static);
1434   int hit = binary_search(methods, name);
1435   if (hit != -1) {
1436     Method* m = methods->at(hit);
1437 
1438     // Do linear search to find matching signature.  First, quick check
1439     // for common case, ignoring overpasses if requested.
1440     if (method_matches(m, signature, skipping_overpass, skipping_static)) return hit;
1441 
1442     // search downwards through overloaded methods
1443     int i;
1444     for (i = hit - 1; i >= 0; --i) {
1445         Method* m = methods->at(i);
1446         assert(m->is_method(), "must be method");
1447         if (m->name() != name) break;
1448         if (method_matches(m, signature, skipping_overpass, skipping_static)) return i;
1449     }
1450     // search upwards
1451     for (i = hit + 1; i < methods->length(); ++i) {
1452         Method* m = methods->at(i);
1453         assert(m->is_method(), "must be method");
1454         if (m->name() != name) break;
1455         if (method_matches(m, signature, skipping_overpass, skipping_static)) return i;
1456     }
1457     // not found
1458 #ifdef ASSERT
1459     int index = (skipping_overpass || skipping_static) ? -1 : linear_search(methods, name, signature);
1460     assert(index == -1, err_msg("binary search should have found entry %d", index));
1461 #endif
1462   }
1463   return -1;
1464 }
1465 int InstanceKlass::find_method_by_name(Symbol* name, int* end) {
1466   return find_method_by_name(methods(), name, end);
1467 }
1468 
1469 int InstanceKlass::find_method_by_name(
1470     Array<Method*>* methods, Symbol* name, int* end_ptr) {
1471   assert(end_ptr != NULL, "just checking");
1472   int start = binary_search(methods, name);
1473   int end = start + 1;
1474   if (start != -1) {
1475     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
1476     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
1477     *end_ptr = end;
1478     return start;
1479   }
1480   return -1;
1481 }
1482 
1483 // uncached_lookup_method searches both the local class methods array and all
1484 // superclasses methods arrays, skipping any overpass methods in superclasses.
1485 Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature, OverpassLookupMode overpass_mode) const {
1486   OverpassLookupMode overpass_local_mode = overpass_mode;
1487   Klass* klass = const_cast<InstanceKlass*>(this);
1488   while (klass != NULL) {
1489     Method* method = InstanceKlass::cast(klass)->find_method_impl(name, signature, overpass_local_mode, find_static);
1490     if (method != NULL) {
1491       return method;
1492     }
1493     klass = InstanceKlass::cast(klass)->super();
1494     overpass_local_mode = skip_overpass;   // Always ignore overpass methods in superclasses
1495   }
1496   return NULL;
1497 }
1498 
1499 #ifdef ASSERT
1500 // search through class hierarchy and return true if this class or
1501 // one of the superclasses was redefined
1502 bool InstanceKlass::has_redefined_this_or_super() const {
1503   const InstanceKlass* klass = this;
1504   while (klass != NULL) {
1505     if (klass->has_been_redefined()) {
1506       return true;
1507     }
1508     klass = InstanceKlass::cast(klass->super());
1509   }
1510   return false;
1511 }
1512 #endif
1513 
1514 // lookup a method in the default methods list then in all transitive interfaces
1515 // Do NOT return private or static methods
1516 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
1517                                                          Symbol* signature) const {
1518   Method* m = NULL;
1519   if (default_methods() != NULL) {
1520     m = find_method(default_methods(), name, signature);
1521   }
1522   // Look up interfaces
1523   if (m == NULL) {
1524     m = lookup_method_in_all_interfaces(name, signature, find_defaults);
1525   }
1526   return m;
1527 }
1528 
1529 // lookup a method in all the interfaces that this class implements
1530 // Do NOT return private or static methods, new in JDK8 which are not externally visible
1531 // They should only be found in the initial InterfaceMethodRef
1532 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
1533                                                        Symbol* signature,
1534                                                        DefaultsLookupMode defaults_mode) const {
1535   Array<Klass*>* all_ifs = transitive_interfaces();
1536   int num_ifs = all_ifs->length();
1537   InstanceKlass *ik = NULL;
1538   for (int i = 0; i < num_ifs; i++) {
1539     ik = InstanceKlass::cast(all_ifs->at(i));
1540     Method* m = ik->lookup_method(name, signature);
1541     if (m != NULL && m->is_public() && !m->is_static() &&
1542         ((defaults_mode != skip_defaults) || !m->is_default_method())) {
1543       return m;
1544     }
1545   }
1546   return NULL;
1547 }
1548 
1549 /* jni_id_for_impl for jfieldIds only */
1550 JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_k, int offset) {
1551   MutexLocker ml(JfieldIdCreation_lock);
1552   // Retry lookup after we got the lock
1553   JNIid* probe = this_k->jni_ids() == NULL ? NULL : this_k->jni_ids()->find(offset);
1554   if (probe == NULL) {
1555     // Slow case, allocate new static field identifier
1556     probe = new JNIid(this_k(), offset, this_k->jni_ids());
1557     this_k->set_jni_ids(probe);
1558   }
1559   return probe;
1560 }
1561 
1562 
1563 /* jni_id_for for jfieldIds only */
1564 JNIid* InstanceKlass::jni_id_for(int offset) {
1565   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
1566   if (probe == NULL) {
1567     probe = jni_id_for_impl(this, offset);
1568   }
1569   return probe;
1570 }
1571 
1572 u2 InstanceKlass::enclosing_method_data(int offset) {
1573   Array<jushort>* inner_class_list = inner_classes();
1574   if (inner_class_list == NULL) {
1575     return 0;
1576   }
1577   int length = inner_class_list->length();
1578   if (length % inner_class_next_offset == 0) {
1579     return 0;
1580   } else {
1581     int index = length - enclosing_method_attribute_size;
1582     assert(offset < enclosing_method_attribute_size, "invalid offset");
1583     return inner_class_list->at(index + offset);
1584   }
1585 }
1586 
1587 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
1588                                                  u2 method_index) {
1589   Array<jushort>* inner_class_list = inner_classes();
1590   assert (inner_class_list != NULL, "_inner_classes list is not set up");
1591   int length = inner_class_list->length();
1592   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
1593     int index = length - enclosing_method_attribute_size;
1594     inner_class_list->at_put(
1595       index + enclosing_method_class_index_offset, class_index);
1596     inner_class_list->at_put(
1597       index + enclosing_method_method_index_offset, method_index);
1598   }
1599 }
1600 
1601 // Lookup or create a jmethodID.
1602 // This code is called by the VMThread and JavaThreads so the
1603 // locking has to be done very carefully to avoid deadlocks
1604 // and/or other cache consistency problems.
1605 //
1606 jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {
1607   size_t idnum = (size_t)method_h->method_idnum();
1608   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
1609   size_t length = 0;
1610   jmethodID id = NULL;
1611 
1612   // We use a double-check locking idiom here because this cache is
1613   // performance sensitive. In the normal system, this cache only
1614   // transitions from NULL to non-NULL which is safe because we use
1615   // release_set_methods_jmethod_ids() to advertise the new cache.
1616   // A partially constructed cache should never be seen by a racing
1617   // thread. We also use release_store_ptr() to save a new jmethodID
1618   // in the cache so a partially constructed jmethodID should never be
1619   // seen either. Cache reads of existing jmethodIDs proceed without a
1620   // lock, but cache writes of a new jmethodID requires uniqueness and
1621   // creation of the cache itself requires no leaks so a lock is
1622   // generally acquired in those two cases.
1623   //
1624   // If the RedefineClasses() API has been used, then this cache can
1625   // grow and we'll have transitions from non-NULL to bigger non-NULL.
1626   // Cache creation requires no leaks and we require safety between all
1627   // cache accesses and freeing of the old cache so a lock is generally
1628   // acquired when the RedefineClasses() API has been used.
1629 
1630   if (jmeths != NULL) {
1631     // the cache already exists
1632     if (!ik_h->idnum_can_increment()) {
1633       // the cache can't grow so we can just get the current values
1634       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1635     } else {
1636       // cache can grow so we have to be more careful
1637       if (Threads::number_of_threads() == 0 ||
1638           SafepointSynchronize::is_at_safepoint()) {
1639         // we're single threaded or at a safepoint - no locking needed
1640         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1641       } else {
1642         MutexLocker ml(JmethodIdCreation_lock);
1643         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1644       }
1645     }
1646   }
1647   // implied else:
1648   // we need to allocate a cache so default length and id values are good
1649 
1650   if (jmeths == NULL ||   // no cache yet
1651       length <= idnum ||  // cache is too short
1652       id == NULL) {       // cache doesn't contain entry
1653 
1654     // This function can be called by the VMThread so we have to do all
1655     // things that might block on a safepoint before grabbing the lock.
1656     // Otherwise, we can deadlock with the VMThread or have a cache
1657     // consistency issue. These vars keep track of what we might have
1658     // to free after the lock is dropped.
1659     jmethodID  to_dealloc_id     = NULL;
1660     jmethodID* to_dealloc_jmeths = NULL;
1661 
1662     // may not allocate new_jmeths or use it if we allocate it
1663     jmethodID* new_jmeths = NULL;
1664     if (length <= idnum) {
1665       // allocate a new cache that might be used
1666       size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
1667       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
1668       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
1669       // cache size is stored in element[0], other elements offset by one
1670       new_jmeths[0] = (jmethodID)size;
1671     }
1672 
1673     // allocate a new jmethodID that might be used
1674     jmethodID new_id = NULL;
1675     if (method_h->is_old() && !method_h->is_obsolete()) {
1676       // The method passed in is old (but not obsolete), we need to use the current version
1677       Method* current_method = ik_h->method_with_idnum((int)idnum);
1678       assert(current_method != NULL, "old and but not obsolete, so should exist");
1679       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);
1680     } else {
1681       // It is the current version of the method or an obsolete method,
1682       // use the version passed in
1683       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());
1684     }
1685 
1686     if (Threads::number_of_threads() == 0 ||
1687         SafepointSynchronize::is_at_safepoint()) {
1688       // we're single threaded or at a safepoint - no locking needed
1689       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
1690                                           &to_dealloc_id, &to_dealloc_jmeths);
1691     } else {
1692       MutexLocker ml(JmethodIdCreation_lock);
1693       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
1694                                           &to_dealloc_id, &to_dealloc_jmeths);
1695     }
1696 
1697     // The lock has been dropped so we can free resources.
1698     // Free up either the old cache or the new cache if we allocated one.
1699     if (to_dealloc_jmeths != NULL) {
1700       FreeHeap(to_dealloc_jmeths);
1701     }
1702     // free up the new ID since it wasn't needed
1703     if (to_dealloc_id != NULL) {
1704       Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);
1705     }
1706   }
1707   return id;
1708 }
1709 
1710 // Figure out how many jmethodIDs haven't been allocated, and make
1711 // sure space for them is pre-allocated.  This makes getting all
1712 // method ids much, much faster with classes with more than 8
1713 // methods, and has a *substantial* effect on performance with jvmti
1714 // code that loads all jmethodIDs for all classes.
1715 void InstanceKlass::ensure_space_for_methodids(int start_offset) {
1716   int new_jmeths = 0;
1717   int length = methods()->length();
1718   for (int index = start_offset; index < length; index++) {
1719     Method* m = methods()->at(index);
1720     jmethodID id = m->find_jmethod_id_or_null();
1721     if (id == NULL) {
1722       new_jmeths++;
1723     }
1724   }
1725   if (new_jmeths != 0) {
1726     Method::ensure_jmethod_ids(class_loader_data(), new_jmeths);
1727   }
1728 }
1729 
1730 // Common code to fetch the jmethodID from the cache or update the
1731 // cache with the new jmethodID. This function should never do anything
1732 // that causes the caller to go to a safepoint or we can deadlock with
1733 // the VMThread or have cache consistency issues.
1734 //
1735 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
1736             instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,
1737             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
1738             jmethodID** to_dealloc_jmeths_p) {
1739   assert(new_id != NULL, "sanity check");
1740   assert(to_dealloc_id_p != NULL, "sanity check");
1741   assert(to_dealloc_jmeths_p != NULL, "sanity check");
1742   assert(Threads::number_of_threads() == 0 ||
1743          SafepointSynchronize::is_at_safepoint() ||
1744          JmethodIdCreation_lock->owned_by_self(), "sanity check");
1745 
1746   // reacquire the cache - we are locked, single threaded or at a safepoint
1747   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
1748   jmethodID  id     = NULL;
1749   size_t     length = 0;
1750 
1751   if (jmeths == NULL ||                         // no cache yet
1752       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
1753     if (jmeths != NULL) {
1754       // copy any existing entries from the old cache
1755       for (size_t index = 0; index < length; index++) {
1756         new_jmeths[index+1] = jmeths[index+1];
1757       }
1758       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
1759     }
1760     ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
1761   } else {
1762     // fetch jmethodID (if any) from the existing cache
1763     id = jmeths[idnum+1];
1764     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
1765   }
1766   if (id == NULL) {
1767     // No matching jmethodID in the existing cache or we have a new
1768     // cache or we just grew the cache. This cache write is done here
1769     // by the first thread to win the foot race because a jmethodID
1770     // needs to be unique once it is generally available.
1771     id = new_id;
1772 
1773     // The jmethodID cache can be read while unlocked so we have to
1774     // make sure the new jmethodID is complete before installing it
1775     // in the cache.
1776     OrderAccess::release_store_ptr(&jmeths[idnum+1], id);
1777   } else {
1778     *to_dealloc_id_p = new_id; // save new id for later delete
1779   }
1780   return id;
1781 }
1782 
1783 
1784 // Common code to get the jmethodID cache length and the jmethodID
1785 // value at index idnum if there is one.
1786 //
1787 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
1788        size_t idnum, size_t *length_p, jmethodID* id_p) {
1789   assert(cache != NULL, "sanity check");
1790   assert(length_p != NULL, "sanity check");
1791   assert(id_p != NULL, "sanity check");
1792 
1793   // cache size is stored in element[0], other elements offset by one
1794   *length_p = (size_t)cache[0];
1795   if (*length_p <= idnum) {  // cache is too short
1796     *id_p = NULL;
1797   } else {
1798     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
1799   }
1800 }
1801 
1802 
1803 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
1804 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
1805   size_t idnum = (size_t)method->method_idnum();
1806   jmethodID* jmeths = methods_jmethod_ids_acquire();
1807   size_t length;                                // length assigned as debugging crumb
1808   jmethodID id = NULL;
1809   if (jmeths != NULL &&                         // If there is a cache
1810       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
1811     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
1812   }
1813   return id;
1814 }
1815 
1816 int nmethodBucketEntry::decrement() {
1817   return Atomic::add(-1, (volatile int *)&_count);
1818 }
1819 
1820 int nmethodBucketEntry::mark_dependent_nmethods(nmethodBucketEntry* deps, DepChange& changes) {
1821   int found = 0, total = 0;
1822   for (nmethodBucketEntry* b = deps; b != NULL; b = b->next(), total++) {






1823     nmethod* nm = b->get_nmethod();
1824     // since dependencies aren't removed until an nmethod becomes a zombie,
1825     // the dependency list may contain nmethods which aren't alive.
1826     if (b->count() > 0 && nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
1827       if (TraceDependencies) {
1828         ResourceMark rm;
1829         tty->print_cr("Marked for deoptimization");
1830         changes.print();
1831         nm->print();
1832         nm->print_dependencies();
1833       }
1834       nm->mark_for_deoptimization();
1835       found++;
1836     }
1837   }
1838   Dependencies::_perf_dependencies_checked_count->inc(total);
1839   return found;
1840 }
1841 
1842 nmethodBucketEntry* nmethodBucketEntry::add_dependent_nmethod(nmethodBucketEntry* deps, nmethod* nm) {






1843   assert_locked_or_safepoint(CodeCache_lock);
1844   for (nmethodBucketEntry* b = deps; b != NULL; b = b->next()) {
1845     if (nm == b->get_nmethod()) {
1846       b->increment();
1847       return deps;
1848     }
1849   }
1850   return new nmethodBucketEntry(nm, deps);
1851 }
1852 
1853 bool nmethodBucketEntry::remove_dependent_nmethod(nmethodBucketEntry* deps, nmethod* nm, bool& found) {






1854   assert_locked_or_safepoint(CodeCache_lock);
1855   for (nmethodBucketEntry* b = deps; b != NULL; b = b->next()) {

1856     if (nm == b->get_nmethod()) {
1857       int val = b->decrement();
1858       guarantee(val >= 0, err_msg("Underflow: %d", val));
1859       found = true;
1860       return (val == 0);
1861     }
1862   }





1863   return false;
1864 }
1865 
1866 nmethodBucketEntry* nmethodBucketEntry::clean_dependent_nmethods(nmethodBucketEntry* deps) {
1867   nmethodBucketEntry* first = deps;
1868   nmethodBucketEntry* last = NULL;
1869   nmethodBucketEntry* b = first;



1870 
1871   while (b != NULL) {
1872     assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));
1873     nmethodBucketEntry* next = b->next();
1874     if (b->count() == 0) {
1875       if (last == NULL) {
1876         first = next;
1877       } else {
1878         last->set_next(next);
1879       }
1880       delete b;
1881       // last stays the same.
1882     } else {
1883       last = b;
1884     }
1885     b = next;
1886   }
1887   return first;
1888 }
1889 
1890 #ifndef PRODUCT
1891 void nmethodBucketEntry::verify(nmethodBucketEntry* deps) {
1892   for (nmethodBucketEntry* b = deps; b != NULL; b = b->next()) {
1893     assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));
1894     assert(b->count() != 0, "empty buckets need to be cleaned");
1895   }
1896 }
1897 
1898 void nmethodBucketEntry::print_dependent_nmethods(nmethodBucketEntry* deps, bool verbose) {
1899   int idx = 0;
1900   for (nmethodBucketEntry* b = deps; b != NULL; b = b->next()) {
1901     nmethod* nm = b->get_nmethod();
1902     tty->print("[%d] count=%d { ", idx++, b->count());
1903     if (!verbose) {
1904       nm->print_on(tty, "nmethod");
1905       tty->print_cr(" } ");
1906     } else {
1907       nm->print();
1908       nm->print_dependencies();
1909       tty->print_cr("--- } ");
1910     }
1911   }
1912 }
1913 
1914 bool nmethodBucketEntry::is_dependent_nmethod(nmethodBucketEntry* deps, nmethod* nm) {
1915   for (nmethodBucketEntry* b = deps; b != NULL; b = b->next()) {
1916     if (nm == b->get_nmethod()) {
1917 #ifdef ASSERT
1918       int count = b->count();
1919       assert(count >= 0, err_msg("count shouldn't be negative: %d", count));
1920 #endif
1921       return true;
1922     }
1923   }
1924   return false;
1925 }
1926 #endif //PRODUCT
1927 
1928 
1929 int nmethodBucket::bucket_index(DepChange& changes) {
1930   if (changes.is_klass_change())               return KlassBucket;
1931   else if (changes.is_call_site_change())      return CallSiteBucket;
1932   else if (changes.is_constant_field_change()) return ConstantFieldBucket;
1933   else {
1934     ShouldNotReachHere();
1935     return -1;
1936   }
1937 }
1938 
1939 //
1940 // Walk the list of dependent nmethods searching for nmethods which
1941 // are dependent on the changes that were passed in and mark them for
1942 // deoptimization.  Returns the number of nmethods found.
1943 //
1944 int nmethodBucket::mark_dependent_nmethods(nmethodBucket* deps, DepChange& changes) {
1945   assert_locked_or_safepoint(CodeCache_lock);
1946   PerfTraceTime pt(Dependencies::_perf_dependency_checking_time);
1947   int found = 0;
1948   if (deps != NULL) {
1949     int idx = bucket_index(changes);
1950     nmethodBucketEntry* b = deps->_buckets[idx];
1951     found = nmethodBucketEntry::mark_dependent_nmethods(b, changes);
1952     Dependencies::_perf_dependencies_context_traversals->inc(1);
1953     Dependencies::_perf_dependencies_invalidated->inc(found);
1954   }
1955   return found;
1956 }
1957 
1958 //
1959 // Add an nmethodBucket to the list of dependencies for this nmethod.
1960 // It's possible that an nmethod has multiple dependencies on this klass
1961 // so a count is kept for each bucket to guarantee that creation and
1962 // deletion of dependencies is consistent. Returns new head of the list.
1963 //
1964 nmethodBucket* nmethodBucket::add_dependent_nmethod(nmethodBucket* b, nmethod* nm) {
1965   assert_locked_or_safepoint(CodeCache_lock);
1966   if (b == NULL) {
1967     b = new nmethodBucket();
1968   }
1969   bool has_deps[Bucket_LIMIT];
1970   for (int i = FIRST_Bucket; i < Bucket_LIMIT; i++) { has_deps[i] = false; }
1971   for (Dependencies::DepStream deps(nm); deps.next(); ) {
1972     switch(deps.type()) {
1973       case Dependencies::call_site_target_value:        has_deps[CallSiteBucket] = true;      break;
1974       case Dependencies::constant_field_value_instance: // fallthru
1975       case Dependencies::constant_field_value_klass:    has_deps[ConstantFieldBucket] = true; break;
1976       default:                                          has_deps[KlassBucket] = true;         break;
1977     }
1978   }
1979   for (int i = FIRST_Bucket; i < Bucket_LIMIT; i++) {
1980     if (has_deps[i]) {
1981       b->_buckets[i] = nmethodBucketEntry::add_dependent_nmethod(b->_buckets[i], nm);
1982     }
1983   }
1984   return b;
1985 }
1986 
1987 //
1988 // Decrement count of the nmethod in the dependency list and remove
1989 // the bucket completely when the count goes to 0.  This method must
1990 // find a corresponding bucket otherwise there's a bug in the
1991 // recording of dependencies. Returns true if the bucket is ready for reclamation.
1992 //
1993 bool nmethodBucket::remove_dependent_nmethod(nmethodBucket* deps, nmethod* nm) {
1994   if (deps != NULL) {
1995     assert_locked_or_safepoint(CodeCache_lock);
1996     bool found = false, removed = false;
1997     for (int i = FIRST_Bucket; i < Bucket_LIMIT; i++) {
1998       bool r = nmethodBucketEntry::remove_dependent_nmethod(deps->_buckets[i], nm, found);
1999       removed = removed || r;
2000     }
2001     if (found) {
2002       return removed;
2003     }
2004   }
2005 #ifdef ASSERT
2006   tty->print_raw_cr("### can't find dependent nmethod");
2007   nm->print();
2008 #endif // ASSERT
2009   ShouldNotReachHere();
2010   return false;
2011 }
2012 
2013 //
2014 // Reclaim all unused buckets. Returns new head of the list.
2015 //
2016 nmethodBucket* nmethodBucket::clean_dependent_nmethods(nmethodBucket* deps) {
2017   if (deps == NULL)  return NULL;
2018   for (int i = FIRST_Bucket; i < Bucket_LIMIT; i++) {
2019     deps->_buckets[i] = nmethodBucketEntry::clean_dependent_nmethods(deps->_buckets[i]);
2020   }
2021   return deps;
2022 }
2023 
2024 int nmethodBucket::release(nmethodBucket* deps) {
2025   if (deps == NULL)  return 0;
2026   int marked = 0;
2027   for (int i = FIRST_Bucket; i < Bucket_LIMIT; i++) {
2028     nmethodBucketEntry* entry = deps->_buckets[i];
2029     while (entry != NULL) {
2030       nmethod* nm = entry->get_nmethod();
2031       if (entry->count() > 0 && nm->is_alive() && !nm->is_marked_for_deoptimization()) {
2032         nm->mark_for_deoptimization();
2033         marked++;
2034       }
2035       nmethodBucketEntry* next = entry->next();
2036       delete entry;
2037       entry = next;
2038     }
2039   }
2040   delete deps;
2041   return marked;
2042 }
2043 
2044 #ifndef PRODUCT
2045 void nmethodBucket::verify(nmethodBucket* deps) {
2046   if (deps == NULL)  return;
2047   for (int i = FIRST_Bucket; i < Bucket_LIMIT; i++) {
2048     nmethodBucketEntry::verify(deps->_buckets[i]);
2049   }
2050 }
2051 
2052 void nmethodBucket::print_dependent_nmethods(nmethodBucket* deps, bool verbose) {
2053   if (deps == NULL)  return;
2054   for (int i = FIRST_Bucket; i < Bucket_LIMIT; i++) {
2055     tty->print_cr("Bucket #%d: ", i);
2056     nmethodBucketEntry::print_dependent_nmethods(deps->_buckets[i], verbose);
2057   }
2058 }
2059 
2060 bool nmethodBucket::is_dependent_nmethod(nmethodBucket* deps, nmethod* nm) {
2061   if (deps == NULL)  return false;
2062   for (int i = FIRST_Bucket; i < Bucket_LIMIT; i++) {
2063     if (nmethodBucketEntry::is_dependent_nmethod(deps->_buckets[i], nm)) {
2064       return true;
2065     }
2066   }
2067   return false;
2068 }
2069 #endif //PRODUCT
2070 
2071 int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {
2072   assert_locked_or_safepoint(CodeCache_lock);
2073   return nmethodBucket::mark_dependent_nmethods(_dependencies, changes);
2074 }
2075 
2076 void InstanceKlass::clean_dependent_nmethods() {
2077   assert_locked_or_safepoint(CodeCache_lock);
2078 
2079   if (has_unloaded_dependent()) {
2080     _dependencies = nmethodBucket::clean_dependent_nmethods(_dependencies);
2081     set_has_unloaded_dependent(false);
2082   }
2083 #ifdef ASSERT
2084   else {
2085     // Verification
2086     nmethodBucket::verify(_dependencies);



2087   }
2088 #endif
2089 }
2090 
2091 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2092   assert_locked_or_safepoint(CodeCache_lock);
2093   _dependencies = nmethodBucket::add_dependent_nmethod(_dependencies, nm);
2094 }
2095 
2096 void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
2097   assert_locked_or_safepoint(CodeCache_lock);
2098 
2099   if (nmethodBucket::remove_dependent_nmethod(_dependencies, nm)) {
2100     set_has_unloaded_dependent(true);
2101   }
2102 }
2103 
2104 #ifndef PRODUCT
2105 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2106   nmethodBucket::print_dependent_nmethods(_dependencies, verbose);
2107 }
2108 
2109 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2110   return nmethodBucket::is_dependent_nmethod(_dependencies, nm);
2111 }
2112 #endif //PRODUCT
2113 
2114 void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
2115   assert(class_loader_data()->is_alive(is_alive), "this klass should be live");
2116   if (is_interface()) {
2117     if (ClassUnloading) {
2118       Klass* impl = implementor();
2119       if (impl != NULL) {
2120         if (!impl->is_loader_alive(is_alive)) {
2121           // remove this guy
2122           Klass** klass = adr_implementor();
2123           assert(klass != NULL, "null klass");
2124           if (klass != NULL) {
2125             *klass = NULL;
2126           }
2127         }
2128       }
2129     }
2130   }
2131 }
2132 
2133 void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {
2134   for (int m = 0; m < methods()->length(); m++) {
2135     MethodData* mdo = methods()->at(m)->method_data();
2136     if (mdo != NULL) {
2137       mdo->clean_method_data(is_alive);
2138     }
2139   }
2140 }
2141 
2142 
2143 static void remove_unshareable_in_class(Klass* k) {
2144   // remove klass's unshareable info
2145   k->remove_unshareable_info();
2146 }
2147 
2148 void InstanceKlass::remove_unshareable_info() {
2149   Klass::remove_unshareable_info();
2150   // Unlink the class
2151   if (is_linked()) {
2152     unlink_class();
2153   }
2154   init_implementor();
2155 
2156   constants()->remove_unshareable_info();
2157 
2158   for (int i = 0; i < methods()->length(); i++) {
2159     Method* m = methods()->at(i);
2160     m->remove_unshareable_info();
2161   }
2162 
2163   // do array classes also.
2164   array_klasses_do(remove_unshareable_in_class);
2165 }
2166 
2167 static void restore_unshareable_in_class(Klass* k, TRAPS) {
2168   // Array classes have null protection domain.
2169   // --> see ArrayKlass::complete_create_array_klass()
2170   k->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);
2171 }
2172 
2173 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
2174   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2175   instanceKlassHandle ik(THREAD, this);
2176 
2177   Array<Method*>* methods = ik->methods();
2178   int num_methods = methods->length();
2179   for (int index2 = 0; index2 < num_methods; ++index2) {
2180     methodHandle m(THREAD, methods->at(index2));
2181     m->restore_unshareable_info(CHECK);
2182   }
2183   if (JvmtiExport::has_redefined_a_class()) {
2184     // Reinitialize vtable because RedefineClasses may have changed some
2185     // entries in this vtable for super classes so the CDS vtable might
2186     // point to old or obsolete entries.  RedefineClasses doesn't fix up
2187     // vtables in the shared system dictionary, only the main one.
2188     // It also redefines the itable too so fix that too.
2189     ResourceMark rm(THREAD);
2190     ik->vtable()->initialize_vtable(false, CHECK);
2191     ik->itable()->initialize_itable(false, CHECK);
2192   }
2193 
2194   // restore constant pool resolved references
2195   ik->constants()->restore_unshareable_info(CHECK);
2196 
2197   ik->array_klasses_do(restore_unshareable_in_class, CHECK);
2198 }
2199 
2200 // returns true IFF is_in_error_state() has been changed as a result of this call.
2201 bool InstanceKlass::check_sharing_error_state() {
2202   assert(DumpSharedSpaces, "should only be called during dumping");
2203   bool old_state = is_in_error_state();
2204 
2205   if (!is_in_error_state()) {
2206     bool bad = false;
2207     for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) {
2208       if (sup->is_in_error_state()) {
2209         bad = true;
2210         break;
2211       }
2212     }
2213     if (!bad) {
2214       Array<Klass*>* interfaces = transitive_interfaces();
2215       for (int i = 0; i < interfaces->length(); i++) {
2216         Klass* iface = interfaces->at(i);
2217         if (InstanceKlass::cast(iface)->is_in_error_state()) {
2218           bad = true;
2219           break;
2220         }
2221       }
2222     }
2223 
2224     if (bad) {
2225       set_in_error_state();
2226     }
2227   }
2228 
2229   return (old_state != is_in_error_state());
2230 }
2231 
2232 static void clear_all_breakpoints(Method* m) {
2233   m->clear_all_breakpoints();
2234 }
2235 
2236 
2237 void InstanceKlass::notify_unload_class(InstanceKlass* ik) {
2238   // notify the debugger
2239   if (JvmtiExport::should_post_class_unload()) {
2240     JvmtiExport::post_class_unload(ik);
2241   }
2242 
2243   // notify ClassLoadingService of class unload
2244   ClassLoadingService::notify_class_unloaded(ik);
2245 }
2246 
2247 void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {
2248   // Clean up C heap
2249   ik->release_C_heap_structures();
2250   ik->constants()->release_C_heap_structures();
2251 }
2252 
2253 void InstanceKlass::release_C_heap_structures() {
2254 
2255   // Can't release the constant pool here because the constant pool can be
2256   // deallocated separately from the InstanceKlass for default methods and
2257   // redefine classes.
2258 
2259   // Deallocate oop map cache
2260   if (_oop_map_cache != NULL) {
2261     delete _oop_map_cache;
2262     _oop_map_cache = NULL;
2263   }
2264 
2265   // Deallocate JNI identifiers for jfieldIDs
2266   JNIid::deallocate(jni_ids());
2267   set_jni_ids(NULL);
2268 
2269   jmethodID* jmeths = methods_jmethod_ids_acquire();
2270   if (jmeths != (jmethodID*)NULL) {
2271     release_set_methods_jmethod_ids(NULL);
2272     FreeHeap(jmeths);
2273   }
2274 
2275   // Deallocate MemberNameTable
2276   {
2277     Mutex* lock_or_null = SafepointSynchronize::is_at_safepoint() ? NULL : MemberNameTable_lock;
2278     MutexLockerEx ml(lock_or_null, Mutex::_no_safepoint_check_flag);
2279     MemberNameTable* mnt = member_names();
2280     if (mnt != NULL) {
2281       delete mnt;
2282       set_member_names(NULL);
2283     }
2284   }
2285 
2286   // release dependencies
2287   int marked = nmethodBucket::release(_dependencies);
2288   assert(marked == 0, "");
2289   _dependencies = NULL;





2290 
2291   // Deallocate breakpoint records
2292   if (breakpoints() != 0x0) {
2293     methods_do(clear_all_breakpoints);
2294     assert(breakpoints() == 0x0, "should have cleared breakpoints");
2295   }
2296 
2297   // deallocate the cached class file
2298   if (_cached_class_file != NULL) {
2299     os::free(_cached_class_file);
2300     _cached_class_file = NULL;
2301   }
2302 
2303   // Decrement symbol reference counts associated with the unloaded class.
2304   if (_name != NULL) _name->decrement_refcount();
2305   // unreference array name derived from this class name (arrays of an unloaded
2306   // class can't be referenced anymore).
2307   if (_array_name != NULL)  _array_name->decrement_refcount();
2308   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension);
2309 
2310   assert(_total_instanceKlass_count >= 1, "Sanity check");
2311   Atomic::dec(&_total_instanceKlass_count);
2312 }
2313 
2314 void InstanceKlass::set_source_debug_extension(char* array, int length) {
2315   if (array == NULL) {
2316     _source_debug_extension = NULL;
2317   } else {
2318     // Adding one to the attribute length in order to store a null terminator
2319     // character could cause an overflow because the attribute length is
2320     // already coded with an u4 in the classfile, but in practice, it's
2321     // unlikely to happen.
2322     assert((length+1) > length, "Overflow checking");
2323     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2324     for (int i = 0; i < length; i++) {
2325       sde[i] = array[i];
2326     }
2327     sde[length] = '\0';
2328     _source_debug_extension = sde;
2329   }
2330 }
2331 
2332 address InstanceKlass::static_field_addr(int offset) {
2333   return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror()));
2334 }
2335 
2336 
2337 const char* InstanceKlass::signature_name() const {
2338   int hash_len = 0;
2339   char hash_buf[40];
2340 
2341   // If this is an anonymous class, append a hash to make the name unique
2342   if (is_anonymous()) {
2343     intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
2344     jio_snprintf(hash_buf, sizeof(hash_buf), "/" UINTX_FORMAT, (uintx)hash);
2345     hash_len = (int)strlen(hash_buf);
2346   }
2347 
2348   // Get the internal name as a c string
2349   const char* src = (const char*) (name()->as_C_string());
2350   const int src_length = (int)strlen(src);
2351 
2352   char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
2353 
2354   // Add L as type indicator
2355   int dest_index = 0;
2356   dest[dest_index++] = 'L';
2357 
2358   // Add the actual class name
2359   for (int src_index = 0; src_index < src_length; ) {
2360     dest[dest_index++] = src[src_index++];
2361   }
2362 
2363   // If we have a hash, append it
2364   for (int hash_index = 0; hash_index < hash_len; ) {
2365     dest[dest_index++] = hash_buf[hash_index++];
2366   }
2367 
2368   // Add the semicolon and the NULL
2369   dest[dest_index++] = ';';
2370   dest[dest_index] = '\0';
2371   return dest;
2372 }
2373 
2374 // different verisons of is_same_class_package
2375 bool InstanceKlass::is_same_class_package(Klass* class2) {
2376   Klass* class1 = this;
2377   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
2378   Symbol* classname1 = class1->name();
2379 
2380   if (class2->oop_is_objArray()) {
2381     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
2382   }
2383   oop classloader2;
2384   if (class2->oop_is_instance()) {
2385     classloader2 = InstanceKlass::cast(class2)->class_loader();
2386   } else {
2387     assert(class2->oop_is_typeArray(), "should be type array");
2388     classloader2 = NULL;
2389   }
2390   Symbol* classname2 = class2->name();
2391 
2392   return InstanceKlass::is_same_class_package(classloader1, classname1,
2393                                               classloader2, classname2);
2394 }
2395 
2396 bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
2397   Klass* class1 = this;
2398   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
2399   Symbol* classname1 = class1->name();
2400 
2401   return InstanceKlass::is_same_class_package(classloader1, classname1,
2402                                               classloader2, classname2);
2403 }
2404 
2405 // return true if two classes are in the same package, classloader
2406 // and classname information is enough to determine a class's package
2407 bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
2408                                           oop class_loader2, Symbol* class_name2) {
2409   if (class_loader1 != class_loader2) {
2410     return false;
2411   } else if (class_name1 == class_name2) {
2412     return true;                // skip painful bytewise comparison
2413   } else {
2414     ResourceMark rm;
2415 
2416     // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly
2417     // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
2418     // Otherwise, we just compare jbyte values between the strings.
2419     const jbyte *name1 = class_name1->base();
2420     const jbyte *name2 = class_name2->base();
2421 
2422     const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
2423     const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
2424 
2425     if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
2426       // One of the two doesn't have a package.  Only return true
2427       // if the other one also doesn't have a package.
2428       return last_slash1 == last_slash2;
2429     } else {
2430       // Skip over '['s
2431       if (*name1 == '[') {
2432         do {
2433           name1++;
2434         } while (*name1 == '[');
2435         if (*name1 != 'L') {
2436           // Something is terribly wrong.  Shouldn't be here.
2437           return false;
2438         }
2439       }
2440       if (*name2 == '[') {
2441         do {
2442           name2++;
2443         } while (*name2 == '[');
2444         if (*name2 != 'L') {
2445           // Something is terribly wrong.  Shouldn't be here.
2446           return false;
2447         }
2448       }
2449 
2450       // Check that package part is identical
2451       int length1 = last_slash1 - name1;
2452       int length2 = last_slash2 - name2;
2453 
2454       return UTF8::equal(name1, length1, name2, length2);
2455     }
2456   }
2457 }
2458 
2459 // Returns true iff super_method can be overridden by a method in targetclassname
2460 // See JSL 3rd edition 8.4.6.1
2461 // Assumes name-signature match
2462 // "this" is InstanceKlass of super_method which must exist
2463 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
2464 bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
2465    // Private methods can not be overridden
2466    if (super_method->is_private()) {
2467      return false;
2468    }
2469    // If super method is accessible, then override
2470    if ((super_method->is_protected()) ||
2471        (super_method->is_public())) {
2472      return true;
2473    }
2474    // Package-private methods are not inherited outside of package
2475    assert(super_method->is_package_private(), "must be package private");
2476    return(is_same_class_package(targetclassloader(), targetclassname));
2477 }
2478 
2479 /* defined for now in jvm.cpp, for historical reasons *--
2480 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
2481                                                      Symbol*& simple_name_result, TRAPS) {
2482   ...
2483 }
2484 */
2485 
2486 // tell if two classes have the same enclosing class (at package level)
2487 bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
2488                                                 Klass* class2_oop, TRAPS) {
2489   if (class2_oop == class1())                       return true;
2490   if (!class2_oop->oop_is_instance())  return false;
2491   instanceKlassHandle class2(THREAD, class2_oop);
2492 
2493   // must be in same package before we try anything else
2494   if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
2495     return false;
2496 
2497   // As long as there is an outer1.getEnclosingClass,
2498   // shift the search outward.
2499   instanceKlassHandle outer1 = class1;
2500   for (;;) {
2501     // As we walk along, look for equalities between outer1 and class2.
2502     // Eventually, the walks will terminate as outer1 stops
2503     // at the top-level class around the original class.
2504     bool ignore_inner_is_member;
2505     Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
2506                                                     CHECK_false);
2507     if (next == NULL)  break;
2508     if (next == class2())  return true;
2509     outer1 = instanceKlassHandle(THREAD, next);
2510   }
2511 
2512   // Now do the same for class2.
2513   instanceKlassHandle outer2 = class2;
2514   for (;;) {
2515     bool ignore_inner_is_member;
2516     Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
2517                                                     CHECK_false);
2518     if (next == NULL)  break;
2519     // Might as well check the new outer against all available values.
2520     if (next == class1())  return true;
2521     if (next == outer1())  return true;
2522     outer2 = instanceKlassHandle(THREAD, next);
2523   }
2524 
2525   // If by this point we have not found an equality between the
2526   // two classes, we know they are in separate package members.
2527   return false;
2528 }
2529 
2530 bool InstanceKlass::find_inner_classes_attr(instanceKlassHandle k, int* ooff, int* noff, TRAPS) {
2531   constantPoolHandle i_cp(THREAD, k->constants());
2532   for (InnerClassesIterator iter(k); !iter.done(); iter.next()) {
2533     int ioff = iter.inner_class_info_index();
2534     if (ioff != 0) {
2535       // Check to see if the name matches the class we're looking for
2536       // before attempting to find the class.
2537       if (i_cp->klass_name_at_matches(k, ioff)) {
2538         Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
2539         if (k() == inner_klass) {
2540           *ooff = iter.outer_class_info_index();
2541           *noff = iter.inner_name_index();
2542           return true;
2543         }
2544       }
2545     }
2546   }
2547   return false;
2548 }
2549 
2550 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle k, bool* inner_is_member, TRAPS) {
2551   instanceKlassHandle outer_klass;
2552   *inner_is_member = false;
2553   int ooff = 0, noff = 0;
2554   if (find_inner_classes_attr(k, &ooff, &noff, THREAD)) {
2555     constantPoolHandle i_cp(THREAD, k->constants());
2556     if (ooff != 0) {
2557       Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
2558       outer_klass = instanceKlassHandle(THREAD, ok);
2559       *inner_is_member = true;
2560     }
2561     if (outer_klass.is_null()) {
2562       // It may be anonymous; try for that.
2563       int encl_method_class_idx = k->enclosing_method_class_index();
2564       if (encl_method_class_idx != 0) {
2565         Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
2566         outer_klass = instanceKlassHandle(THREAD, ok);
2567         *inner_is_member = false;
2568       }
2569     }
2570   }
2571 
2572   // If no inner class attribute found for this class.
2573   if (outer_klass.is_null())  return NULL;
2574 
2575   // Throws an exception if outer klass has not declared k as an inner klass
2576   // We need evidence that each klass knows about the other, or else
2577   // the system could allow a spoof of an inner class to gain access rights.
2578   Reflection::check_for_inner_class(outer_klass, k, *inner_is_member, CHECK_NULL);
2579   return outer_klass();
2580 }
2581 
2582 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
2583   jint access = access_flags().as_int();
2584 
2585   // But check if it happens to be member class.
2586   instanceKlassHandle ik(THREAD, this);
2587   InnerClassesIterator iter(ik);
2588   for (; !iter.done(); iter.next()) {
2589     int ioff = iter.inner_class_info_index();
2590     // Inner class attribute can be zero, skip it.
2591     // Strange but true:  JVM spec. allows null inner class refs.
2592     if (ioff == 0) continue;
2593 
2594     // only look at classes that are already loaded
2595     // since we are looking for the flags for our self.
2596     Symbol* inner_name = ik->constants()->klass_name_at(ioff);
2597     if ((ik->name() == inner_name)) {
2598       // This is really a member class.
2599       access = iter.inner_access_flags();
2600       break;
2601     }
2602   }
2603   // Remember to strip ACC_SUPER bit
2604   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
2605 }
2606 
2607 jint InstanceKlass::jvmti_class_status() const {
2608   jint result = 0;
2609 
2610   if (is_linked()) {
2611     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
2612   }
2613 
2614   if (is_initialized()) {
2615     assert(is_linked(), "Class status is not consistent");
2616     result |= JVMTI_CLASS_STATUS_INITIALIZED;
2617   }
2618   if (is_in_error_state()) {
2619     result |= JVMTI_CLASS_STATUS_ERROR;
2620   }
2621   return result;
2622 }
2623 
2624 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
2625   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2626   int method_table_offset_in_words = ioe->offset()/wordSize;
2627   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2628                        / itableOffsetEntry::size();
2629 
2630   for (int cnt = 0 ; ; cnt ++, ioe ++) {
2631     // If the interface isn't implemented by the receiver class,
2632     // the VM should throw IncompatibleClassChangeError.
2633     if (cnt >= nof_interfaces) {
2634       THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
2635     }
2636 
2637     Klass* ik = ioe->interface_klass();
2638     if (ik == holder) break;
2639   }
2640 
2641   itableMethodEntry* ime = ioe->first_method_entry(this);
2642   Method* m = ime[index].method();
2643   if (m == NULL) {
2644     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
2645   }
2646   return m;
2647 }
2648 
2649 
2650 #if INCLUDE_JVMTI
2651 // update default_methods for redefineclasses for methods that are
2652 // not yet in the vtable due to concurrent subclass define and superinterface
2653 // redefinition
2654 // Note: those in the vtable, should have been updated via adjust_method_entries
2655 void InstanceKlass::adjust_default_methods(InstanceKlass* holder, bool* trace_name_printed) {
2656   // search the default_methods for uses of either obsolete or EMCP methods
2657   if (default_methods() != NULL) {
2658     for (int index = 0; index < default_methods()->length(); index ++) {
2659       Method* old_method = default_methods()->at(index);
2660       if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) {
2661         continue; // skip uninteresting entries
2662       }
2663       assert(!old_method->is_deleted(), "default methods may not be deleted");
2664 
2665       Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum());
2666 
2667       assert(new_method != NULL, "method_with_idnum() should not be NULL");
2668       assert(old_method != new_method, "sanity check");
2669 
2670       default_methods()->at_put(index, new_method);
2671       if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
2672         if (!(*trace_name_printed)) {
2673           // RC_TRACE_MESG macro has an embedded ResourceMark
2674           RC_TRACE_MESG(("adjust: klassname=%s default methods from name=%s",
2675                          external_name(),
2676                          old_method->method_holder()->external_name()));
2677           *trace_name_printed = true;
2678         }
2679         RC_TRACE(0x00100000, ("default method update: %s(%s) ",
2680                               new_method->name()->as_C_string(),
2681                               new_method->signature()->as_C_string()));
2682       }
2683     }
2684   }
2685 }
2686 #endif // INCLUDE_JVMTI
2687 
2688 // On-stack replacement stuff
2689 void InstanceKlass::add_osr_nmethod(nmethod* n) {
2690   // only one compilation can be active
2691   {
2692     // This is a short non-blocking critical region, so the no safepoint check is ok.
2693     MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
2694     assert(n->is_osr_method(), "wrong kind of nmethod");
2695     n->set_osr_link(osr_nmethods_head());
2696     set_osr_nmethods_head(n);
2697     // Raise the highest osr level if necessary
2698     if (TieredCompilation) {
2699       Method* m = n->method();
2700       m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
2701     }
2702   }
2703 
2704   // Get rid of the osr methods for the same bci that have lower levels.
2705   if (TieredCompilation) {
2706     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
2707       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
2708       if (inv != NULL && inv->is_in_use()) {
2709         inv->make_not_entrant();
2710       }
2711     }
2712   }
2713 }
2714 
2715 
2716 void InstanceKlass::remove_osr_nmethod(nmethod* n) {
2717   // This is a short non-blocking critical region, so the no safepoint check is ok.
2718   MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
2719   assert(n->is_osr_method(), "wrong kind of nmethod");
2720   nmethod* last = NULL;
2721   nmethod* cur  = osr_nmethods_head();
2722   int max_level = CompLevel_none;  // Find the max comp level excluding n
2723   Method* m = n->method();
2724   // Search for match
2725   while(cur != NULL && cur != n) {
2726     if (TieredCompilation && m == cur->method()) {
2727       // Find max level before n
2728       max_level = MAX2(max_level, cur->comp_level());
2729     }
2730     last = cur;
2731     cur = cur->osr_link();
2732   }
2733   nmethod* next = NULL;
2734   if (cur == n) {
2735     next = cur->osr_link();
2736     if (last == NULL) {
2737       // Remove first element
2738       set_osr_nmethods_head(next);
2739     } else {
2740       last->set_osr_link(next);
2741     }
2742   }
2743   n->set_osr_link(NULL);
2744   if (TieredCompilation) {
2745     cur = next;
2746     while (cur != NULL) {
2747       // Find max level after n
2748       if (m == cur->method()) {
2749         max_level = MAX2(max_level, cur->comp_level());
2750       }
2751       cur = cur->osr_link();
2752     }
2753     m->set_highest_osr_comp_level(max_level);
2754   }
2755 }
2756 
2757 int InstanceKlass::mark_osr_nmethods(const Method* m) {
2758   // This is a short non-blocking critical region, so the no safepoint check is ok.
2759   MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
2760   nmethod* osr = osr_nmethods_head();
2761   int found = 0;
2762   while (osr != NULL) {
2763     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
2764     if (osr->method() == m) {
2765       osr->mark_for_deoptimization();
2766       found++;
2767     }
2768     osr = osr->osr_link();
2769   }
2770   return found;
2771 }
2772 
2773 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
2774   // This is a short non-blocking critical region, so the no safepoint check is ok.
2775   MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
2776   nmethod* osr = osr_nmethods_head();
2777   nmethod* best = NULL;
2778   while (osr != NULL) {
2779     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
2780     // There can be a time when a c1 osr method exists but we are waiting
2781     // for a c2 version. When c2 completes its osr nmethod we will trash
2782     // the c1 version and only be able to find the c2 version. However
2783     // while we overflow in the c1 code at back branches we don't want to
2784     // try and switch to the same code as we are already running
2785 
2786     if (osr->method() == m &&
2787         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
2788       if (match_level) {
2789         if (osr->comp_level() == comp_level) {
2790           // Found a match - return it.
2791           return osr;
2792         }
2793       } else {
2794         if (best == NULL || (osr->comp_level() > best->comp_level())) {
2795           if (osr->comp_level() == CompLevel_highest_tier) {
2796             // Found the best possible - return it.
2797             return osr;
2798           }
2799           best = osr;
2800         }
2801       }
2802     }
2803     osr = osr->osr_link();
2804   }
2805   if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
2806     return best;
2807   }
2808   return NULL;
2809 }
2810 
2811 bool InstanceKlass::add_member_name(Handle mem_name) {
2812   jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);
2813   MutexLocker ml(MemberNameTable_lock);
2814   DEBUG_ONLY(No_Safepoint_Verifier nsv);
2815 
2816   // Check if method has been redefined while taking out MemberNameTable_lock, if so
2817   // return false.  We cannot cache obsolete methods. They will crash when the function
2818   // is called!
2819   Method* method = (Method*)java_lang_invoke_MemberName::vmtarget(mem_name());
2820   if (method->is_obsolete()) {
2821     return false;
2822   } else if (method->is_old()) {
2823     // Replace method with redefined version
2824     java_lang_invoke_MemberName::set_vmtarget(mem_name(), method_with_idnum(method->method_idnum()));
2825   }
2826 
2827   if (_member_names == NULL) {
2828     _member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count());
2829   }
2830   _member_names->add_member_name(mem_name_wref);
2831   return true;
2832 }
2833 
2834 // -----------------------------------------------------------------------------------------------------
2835 // Printing
2836 
2837 #ifndef PRODUCT
2838 
2839 #define BULLET  " - "
2840 
2841 static const char* state_names[] = {
2842   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
2843 };
2844 
2845 static void print_vtable(intptr_t* start, int len, outputStream* st) {
2846   for (int i = 0; i < len; i++) {
2847     intptr_t e = start[i];
2848     st->print("%d : " INTPTR_FORMAT, i, e);
2849     if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {
2850       st->print(" ");
2851       ((Metadata*)e)->print_value_on(st);
2852     }
2853     st->cr();
2854   }
2855 }
2856 
2857 void InstanceKlass::print_on(outputStream* st) const {
2858   assert(is_klass(), "must be klass");
2859   Klass::print_on(st);
2860 
2861   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
2862   st->print(BULLET"klass size:        %d", size());                               st->cr();
2863   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
2864   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
2865   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
2866   st->print(BULLET"super:             "); super()->print_value_on_maybe_null(st); st->cr();
2867   st->print(BULLET"sub:               ");
2868   Klass* sub = subklass();
2869   int n;
2870   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
2871     if (n < MaxSubklassPrintSize) {
2872       sub->print_value_on(st);
2873       st->print("   ");
2874     }
2875   }
2876   if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);
2877   st->cr();
2878 
2879   if (is_interface()) {
2880     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
2881     if (nof_implementors() == 1) {
2882       st->print_cr(BULLET"implementor:    ");
2883       st->print("   ");
2884       implementor()->print_value_on(st);
2885       st->cr();
2886     }
2887   }
2888 
2889   st->print(BULLET"arrays:            "); array_klasses()->print_value_on_maybe_null(st); st->cr();
2890   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
2891   if (Verbose || WizardMode) {
2892     Array<Method*>* method_array = methods();
2893     for (int i = 0; i < method_array->length(); i++) {
2894       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
2895     }
2896   }
2897   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
2898   st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
2899   if (Verbose && default_methods() != NULL) {
2900     Array<Method*>* method_array = default_methods();
2901     for (int i = 0; i < method_array->length(); i++) {
2902       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
2903     }
2904   }
2905   if (default_vtable_indices() != NULL) {
2906     st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
2907   }
2908   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
2909   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
2910   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
2911   if (class_loader_data() != NULL) {
2912     st->print(BULLET"class loader data:  ");
2913     class_loader_data()->print_value_on(st);
2914     st->cr();
2915   }
2916   st->print(BULLET"host class:        "); host_klass()->print_value_on_maybe_null(st); st->cr();
2917   if (source_file_name() != NULL) {
2918     st->print(BULLET"source file:       ");
2919     source_file_name()->print_value_on(st);
2920     st->cr();
2921   }
2922   if (source_debug_extension() != NULL) {
2923     st->print(BULLET"source debug extension:       ");
2924     st->print("%s", source_debug_extension());
2925     st->cr();
2926   }
2927   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
2928   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
2929   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
2930   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
2931   {
2932     bool have_pv = false;
2933     // previous versions are linked together through the InstanceKlass
2934     for (InstanceKlass* pv_node = _previous_versions;
2935          pv_node != NULL;
2936          pv_node = pv_node->previous_versions()) {
2937       if (!have_pv)
2938         st->print(BULLET"previous version:  ");
2939       have_pv = true;
2940       pv_node->constants()->print_value_on(st);
2941     }
2942     if (have_pv) st->cr();
2943   }
2944 
2945   if (generic_signature() != NULL) {
2946     st->print(BULLET"generic signature: ");
2947     generic_signature()->print_value_on(st);
2948     st->cr();
2949   }
2950   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
2951   st->print(BULLET"java mirror:       "); java_mirror()->print_value_on(st);       st->cr();
2952   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable());  st->cr();
2953   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
2954   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();
2955   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
2956   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
2957   FieldPrinter print_static_field(st);
2958   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
2959   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
2960   FieldPrinter print_nonstatic_field(st);
2961   ((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);
2962 
2963   st->print(BULLET"non-static oop maps: ");
2964   OopMapBlock* map     = start_of_nonstatic_oop_maps();
2965   OopMapBlock* end_map = map + nonstatic_oop_map_count();
2966   while (map < end_map) {
2967     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
2968     map++;
2969   }
2970   st->cr();
2971 }
2972 
2973 #endif //PRODUCT
2974 
2975 void InstanceKlass::print_value_on(outputStream* st) const {
2976   assert(is_klass(), "must be klass");
2977   if (Verbose || WizardMode)  access_flags().print_on(st);
2978   name()->print_value_on(st);
2979 }
2980 
2981 #ifndef PRODUCT
2982 
2983 void FieldPrinter::do_field(fieldDescriptor* fd) {
2984   _st->print(BULLET);
2985    if (_obj == NULL) {
2986      fd->print_on(_st);
2987      _st->cr();
2988    } else {
2989      fd->print_on_for(_st, _obj);
2990      _st->cr();
2991    }
2992 }
2993 
2994 
2995 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
2996   Klass::oop_print_on(obj, st);
2997 
2998   if (this == SystemDictionary::String_klass()) {
2999     typeArrayOop value  = java_lang_String::value(obj);
3000     juint        offset = java_lang_String::offset(obj);
3001     juint        length = java_lang_String::length(obj);
3002     if (value != NULL &&
3003         value->is_typeArray() &&
3004         offset          <= (juint) value->length() &&
3005         offset + length <= (juint) value->length()) {
3006       st->print(BULLET"string: ");
3007       java_lang_String::print(obj, st);
3008       st->cr();
3009       if (!WizardMode)  return;  // that is enough
3010     }
3011   }
3012 
3013   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
3014   FieldPrinter print_field(st, obj);
3015   do_nonstatic_fields(&print_field);
3016 
3017   if (this == SystemDictionary::Class_klass()) {
3018     st->print(BULLET"signature: ");
3019     java_lang_Class::print_signature(obj, st);
3020     st->cr();
3021     Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
3022     st->print(BULLET"fake entry for mirror: ");
3023     mirrored_klass->print_value_on_maybe_null(st);
3024     st->cr();
3025     Klass* array_klass = java_lang_Class::array_klass(obj);
3026     st->print(BULLET"fake entry for array: ");
3027     array_klass->print_value_on_maybe_null(st);
3028     st->cr();
3029     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
3030     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
3031     Klass* real_klass = java_lang_Class::as_Klass(obj);
3032     if (real_klass != NULL && real_klass->oop_is_instance()) {
3033       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3034     }
3035   } else if (this == SystemDictionary::MethodType_klass()) {
3036     st->print(BULLET"signature: ");
3037     java_lang_invoke_MethodType::print_signature(obj, st);
3038     st->cr();
3039   }
3040 }
3041 
3042 #endif //PRODUCT
3043 
3044 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
3045   st->print("a ");
3046   name()->print_value_on(st);
3047   obj->print_address_on(st);
3048   if (this == SystemDictionary::String_klass()
3049       && java_lang_String::value(obj) != NULL) {
3050     ResourceMark rm;
3051     int len = java_lang_String::length(obj);
3052     int plen = (len < 24 ? len : 12);
3053     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
3054     st->print(" = \"%s\"", str);
3055     if (len > plen)
3056       st->print("...[%d]", len);
3057   } else if (this == SystemDictionary::Class_klass()) {
3058     Klass* k = java_lang_Class::as_Klass(obj);
3059     st->print(" = ");
3060     if (k != NULL) {
3061       k->print_value_on(st);
3062     } else {
3063       const char* tname = type2name(java_lang_Class::primitive_type(obj));
3064       st->print("%s", tname ? tname : "type?");
3065     }
3066   } else if (this == SystemDictionary::MethodType_klass()) {
3067     st->print(" = ");
3068     java_lang_invoke_MethodType::print_signature(obj, st);
3069   } else if (java_lang_boxing_object::is_instance(obj)) {
3070     st->print(" = ");
3071     java_lang_boxing_object::print(obj, st);
3072   } else if (this == SystemDictionary::LambdaForm_klass()) {
3073     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
3074     if (vmentry != NULL) {
3075       st->print(" => ");
3076       vmentry->print_value_on(st);
3077     }
3078   } else if (this == SystemDictionary::MemberName_klass()) {
3079     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
3080     if (vmtarget != NULL) {
3081       st->print(" = ");
3082       vmtarget->print_value_on(st);
3083     } else {
3084       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
3085       st->print(".");
3086       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
3087     }
3088   }
3089 }
3090 
3091 const char* InstanceKlass::internal_name() const {
3092   return external_name();
3093 }
3094 
3095 #if INCLUDE_SERVICES
3096 // Size Statistics
3097 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
3098   Klass::collect_statistics(sz);
3099 
3100   sz->_inst_size  = HeapWordSize * size_helper();
3101   sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());
3102   sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());
3103   sz->_nonstatic_oopmap_bytes = HeapWordSize *
3104         ((is_interface() || is_anonymous()) ?
3105          align_object_offset(nonstatic_oop_map_size()) :
3106          nonstatic_oop_map_size());
3107 
3108   int n = 0;
3109   n += (sz->_methods_array_bytes         = sz->count_array(methods()));
3110   n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
3111   n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
3112   n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
3113   n += (sz->_fields_bytes                = sz->count_array(fields()));
3114   n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
3115   sz->_ro_bytes += n;
3116 
3117   const ConstantPool* cp = constants();
3118   if (cp) {
3119     cp->collect_statistics(sz);
3120   }
3121 
3122   const Annotations* anno = annotations();
3123   if (anno) {
3124     anno->collect_statistics(sz);
3125   }
3126 
3127   const Array<Method*>* methods_array = methods();
3128   if (methods()) {
3129     for (int i = 0; i < methods_array->length(); i++) {
3130       Method* method = methods_array->at(i);
3131       if (method) {
3132         sz->_method_count ++;
3133         method->collect_statistics(sz);
3134       }
3135     }
3136   }
3137 }
3138 #endif // INCLUDE_SERVICES
3139 
3140 // Verification
3141 
3142 class VerifyFieldClosure: public OopClosure {
3143  protected:
3144   template <class T> void do_oop_work(T* p) {
3145     oop obj = oopDesc::load_decode_heap_oop(p);
3146     if (!obj->is_oop_or_null()) {
3147       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);
3148       Universe::print();
3149       guarantee(false, "boom");
3150     }
3151   }
3152  public:
3153   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
3154   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
3155 };
3156 
3157 void InstanceKlass::verify_on(outputStream* st) {
3158 #ifndef PRODUCT
3159   // Avoid redundant verifies, this really should be in product.
3160   if (_verify_count == Universe::verify_count()) return;
3161   _verify_count = Universe::verify_count();
3162 #endif
3163 
3164   // Verify Klass
3165   Klass::verify_on(st);
3166 
3167   // Verify that klass is present in ClassLoaderData
3168   guarantee(class_loader_data()->contains_klass(this),
3169             "this class isn't found in class loader data");
3170 
3171   // Verify vtables
3172   if (is_linked()) {
3173     ResourceMark rm;
3174     // $$$ This used to be done only for m/s collections.  Doing it
3175     // always seemed a valid generalization.  (DLD -- 6/00)
3176     vtable()->verify(st);
3177   }
3178 
3179   // Verify first subklass
3180   if (subklass() != NULL) {
3181     guarantee(subklass()->is_klass(), "should be klass");
3182   }
3183 
3184   // Verify siblings
3185   Klass* super = this->super();
3186   Klass* sib = next_sibling();
3187   if (sib != NULL) {
3188     if (sib == this) {
3189       fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));
3190     }
3191 
3192     guarantee(sib->is_klass(), "should be klass");
3193     guarantee(sib->super() == super, "siblings should have same superklass");
3194   }
3195 
3196   // Verify implementor fields
3197   Klass* im = implementor();
3198   if (im != NULL) {
3199     guarantee(is_interface(), "only interfaces should have implementor set");
3200     guarantee(im->is_klass(), "should be klass");
3201     guarantee(!im->is_interface() || im == this,
3202       "implementors cannot be interfaces");
3203   }
3204 
3205   // Verify local interfaces
3206   if (local_interfaces()) {
3207     Array<Klass*>* local_interfaces = this->local_interfaces();
3208     for (int j = 0; j < local_interfaces->length(); j++) {
3209       Klass* e = local_interfaces->at(j);
3210       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
3211     }
3212   }
3213 
3214   // Verify transitive interfaces
3215   if (transitive_interfaces() != NULL) {
3216     Array<Klass*>* transitive_interfaces = this->transitive_interfaces();
3217     for (int j = 0; j < transitive_interfaces->length(); j++) {
3218       Klass* e = transitive_interfaces->at(j);
3219       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
3220     }
3221   }
3222 
3223   // Verify methods
3224   if (methods() != NULL) {
3225     Array<Method*>* methods = this->methods();
3226     for (int j = 0; j < methods->length(); j++) {
3227       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3228     }
3229     for (int j = 0; j < methods->length() - 1; j++) {
3230       Method* m1 = methods->at(j);
3231       Method* m2 = methods->at(j + 1);
3232       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3233     }
3234   }
3235 
3236   // Verify method ordering
3237   if (method_ordering() != NULL) {
3238     Array<int>* method_ordering = this->method_ordering();
3239     int length = method_ordering->length();
3240     if (JvmtiExport::can_maintain_original_method_order() ||
3241         ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
3242       guarantee(length == methods()->length(), "invalid method ordering length");
3243       jlong sum = 0;
3244       for (int j = 0; j < length; j++) {
3245         int original_index = method_ordering->at(j);
3246         guarantee(original_index >= 0, "invalid method ordering index");
3247         guarantee(original_index < length, "invalid method ordering index");
3248         sum += original_index;
3249       }
3250       // Verify sum of indices 0,1,...,length-1
3251       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
3252     } else {
3253       guarantee(length == 0, "invalid method ordering length");
3254     }
3255   }
3256 
3257   // Verify default methods
3258   if (default_methods() != NULL) {
3259     Array<Method*>* methods = this->default_methods();
3260     for (int j = 0; j < methods->length(); j++) {
3261       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3262     }
3263     for (int j = 0; j < methods->length() - 1; j++) {
3264       Method* m1 = methods->at(j);
3265       Method* m2 = methods->at(j + 1);
3266       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3267     }
3268   }
3269 
3270   // Verify JNI static field identifiers
3271   if (jni_ids() != NULL) {
3272     jni_ids()->verify(this);
3273   }
3274 
3275   // Verify other fields
3276   if (array_klasses() != NULL) {
3277     guarantee(array_klasses()->is_klass(), "should be klass");
3278   }
3279   if (constants() != NULL) {
3280     guarantee(constants()->is_constantPool(), "should be constant pool");
3281   }
3282   const Klass* host = host_klass();
3283   if (host != NULL) {
3284     guarantee(host->is_klass(), "should be klass");
3285   }
3286 }
3287 
3288 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
3289   Klass::oop_verify_on(obj, st);
3290   VerifyFieldClosure blk;
3291   obj->oop_iterate_no_header(&blk);
3292 }
3293 
3294 
3295 // JNIid class for jfieldIDs only
3296 // Note to reviewers:
3297 // These JNI functions are just moved over to column 1 and not changed
3298 // in the compressed oops workspace.
3299 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
3300   _holder = holder;
3301   _offset = offset;
3302   _next = next;
3303   debug_only(_is_static_field_id = false;)
3304 }
3305 
3306 
3307 JNIid* JNIid::find(int offset) {
3308   JNIid* current = this;
3309   while (current != NULL) {
3310     if (current->offset() == offset) return current;
3311     current = current->next();
3312   }
3313   return NULL;
3314 }
3315 
3316 void JNIid::deallocate(JNIid* current) {
3317   while (current != NULL) {
3318     JNIid* next = current->next();
3319     delete current;
3320     current = next;
3321   }
3322 }
3323 
3324 
3325 void JNIid::verify(Klass* holder) {
3326   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
3327   int end_field_offset;
3328   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
3329 
3330   JNIid* current = this;
3331   while (current != NULL) {
3332     guarantee(current->holder() == holder, "Invalid klass in JNIid");
3333 #ifdef ASSERT
3334     int o = current->offset();
3335     if (current->is_static_field_id()) {
3336       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
3337     }
3338 #endif
3339     current = current->next();
3340   }
3341 }
3342 
3343 
3344 #ifdef ASSERT
3345 void InstanceKlass::set_init_state(ClassState state) {
3346   bool good_state = is_shared() ? (_init_state <= state)
3347                                                : (_init_state < state);
3348   assert(good_state || state == allocated, "illegal state transition");
3349   _init_state = (u1)state;
3350 }
3351 #endif
3352 
3353 
3354 
3355 // RedefineClasses() support for previous versions:
3356 int InstanceKlass::_previous_version_count = 0;
3357 
3358 // Purge previous versions before adding new previous versions of the class.
3359 void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
3360   if (ik->previous_versions() != NULL) {
3361     // This klass has previous versions so see what we can cleanup
3362     // while it is safe to do so.
3363 
3364     int deleted_count = 0;    // leave debugging breadcrumbs
3365     int live_count = 0;
3366     ClassLoaderData* loader_data = ik->class_loader_data();
3367     assert(loader_data != NULL, "should never be null");
3368 
3369     // RC_TRACE macro has an embedded ResourceMark
3370     RC_TRACE(0x00000200, ("purge: %s: previous versions", ik->external_name()));
3371 
3372     // previous versions are linked together through the InstanceKlass
3373     InstanceKlass* pv_node = ik->previous_versions();
3374     InstanceKlass* last = ik;
3375     int version = 0;
3376 
3377     // check the previous versions list
3378     for (; pv_node != NULL; ) {
3379 
3380       ConstantPool* pvcp = pv_node->constants();
3381       assert(pvcp != NULL, "cp ref was unexpectedly cleared");
3382 
3383       if (!pvcp->on_stack()) {
3384         // If the constant pool isn't on stack, none of the methods
3385         // are executing.  Unlink this previous_version.
3386         // The previous version InstanceKlass is on the ClassLoaderData deallocate list
3387         // so will be deallocated during the next phase of class unloading.
3388         RC_TRACE(0x00000200, ("purge: previous version " INTPTR_FORMAT " is dead",
3389                               pv_node));
3390         // For debugging purposes.
3391         pv_node->set_is_scratch_class();
3392         pv_node->class_loader_data()->add_to_deallocate_list(pv_node);
3393         pv_node = pv_node->previous_versions();
3394         last->link_previous_versions(pv_node);
3395         deleted_count++;
3396         version++;
3397         continue;
3398       } else {
3399         RC_TRACE(0x00000200, ("purge: previous version " INTPTR_FORMAT " is alive",
3400                               pv_node));
3401         assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
3402         guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
3403         live_count++;
3404       }
3405 
3406       // At least one method is live in this previous version.
3407       // Reset dead EMCP methods not to get breakpoints.
3408       // All methods are deallocated when all of the methods for this class are no
3409       // longer running.
3410       Array<Method*>* method_refs = pv_node->methods();
3411       if (method_refs != NULL) {
3412         RC_TRACE(0x00000200, ("purge: previous methods length=%d",
3413           method_refs->length()));
3414         for (int j = 0; j < method_refs->length(); j++) {
3415           Method* method = method_refs->at(j);
3416 
3417           if (!method->on_stack()) {
3418             // no breakpoints for non-running methods
3419             if (method->is_running_emcp()) {
3420               method->set_running_emcp(false);
3421             }
3422           } else {
3423             assert (method->is_obsolete() || method->is_running_emcp(),
3424                     "emcp method cannot run after emcp bit is cleared");
3425             // RC_TRACE macro has an embedded ResourceMark
3426             RC_TRACE(0x00000200,
3427               ("purge: %s(%s): prev method @%d in version @%d is alive",
3428               method->name()->as_C_string(),
3429               method->signature()->as_C_string(), j, version));
3430           }
3431         }
3432       }
3433       // next previous version
3434       last = pv_node;
3435       pv_node = pv_node->previous_versions();
3436       version++;
3437     }
3438     RC_TRACE(0x00000200,
3439       ("purge: previous version stats: live=%d, deleted=%d", live_count,
3440       deleted_count));
3441   }
3442 }
3443 
3444 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,
3445                                                 int emcp_method_count) {
3446   int obsolete_method_count = old_methods->length() - emcp_method_count;
3447 
3448   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
3449       _previous_versions != NULL) {
3450     // We have a mix of obsolete and EMCP methods so we have to
3451     // clear out any matching EMCP method entries the hard way.
3452     int local_count = 0;
3453     for (int i = 0; i < old_methods->length(); i++) {
3454       Method* old_method = old_methods->at(i);
3455       if (old_method->is_obsolete()) {
3456         // only obsolete methods are interesting
3457         Symbol* m_name = old_method->name();
3458         Symbol* m_signature = old_method->signature();
3459 
3460         // previous versions are linked together through the InstanceKlass
3461         int j = 0;
3462         for (InstanceKlass* prev_version = _previous_versions;
3463              prev_version != NULL;
3464              prev_version = prev_version->previous_versions(), j++) {
3465 
3466           Array<Method*>* method_refs = prev_version->methods();
3467           for (int k = 0; k < method_refs->length(); k++) {
3468             Method* method = method_refs->at(k);
3469 
3470             if (!method->is_obsolete() &&
3471                 method->name() == m_name &&
3472                 method->signature() == m_signature) {
3473               // The current RedefineClasses() call has made all EMCP
3474               // versions of this method obsolete so mark it as obsolete
3475               RC_TRACE(0x00000400,
3476                 ("add: %s(%s): flush obsolete method @%d in version @%d",
3477                 m_name->as_C_string(), m_signature->as_C_string(), k, j));
3478 
3479               method->set_is_obsolete();
3480               break;
3481             }
3482           }
3483 
3484           // The previous loop may not find a matching EMCP method, but
3485           // that doesn't mean that we can optimize and not go any
3486           // further back in the PreviousVersion generations. The EMCP
3487           // method for this generation could have already been made obsolete,
3488           // but there still may be an older EMCP method that has not
3489           // been made obsolete.
3490         }
3491 
3492         if (++local_count >= obsolete_method_count) {
3493           // no more obsolete methods so bail out now
3494           break;
3495         }
3496       }
3497     }
3498   }
3499 }
3500 
3501 // Save the scratch_class as the previous version if any of the methods are running.
3502 // The previous_versions are used to set breakpoints in EMCP methods and they are
3503 // also used to clean MethodData links to redefined methods that are no longer running.
3504 void InstanceKlass::add_previous_version(instanceKlassHandle scratch_class,
3505                                          int emcp_method_count) {
3506   assert(Thread::current()->is_VM_thread(),
3507          "only VMThread can add previous versions");
3508 
3509   // RC_TRACE macro has an embedded ResourceMark
3510   RC_TRACE(0x00000400, ("adding previous version ref for %s, EMCP_cnt=%d",
3511     scratch_class->external_name(), emcp_method_count));
3512 
3513   // Clean out old previous versions
3514   purge_previous_versions(this);
3515 
3516   // Mark newly obsolete methods in remaining previous versions.  An EMCP method from
3517   // a previous redefinition may be made obsolete by this redefinition.
3518   Array<Method*>* old_methods = scratch_class->methods();
3519   mark_newly_obsolete_methods(old_methods, emcp_method_count);
3520 
3521   // If the constant pool for this previous version of the class
3522   // is not marked as being on the stack, then none of the methods
3523   // in this previous version of the class are on the stack so
3524   // we don't need to add this as a previous version.
3525   ConstantPool* cp_ref = scratch_class->constants();
3526   if (!cp_ref->on_stack()) {
3527     RC_TRACE(0x00000400, ("add: scratch class not added; no methods are running"));
3528     // For debugging purposes.
3529     scratch_class->set_is_scratch_class();
3530     scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class());
3531     // Update count for class unloading.
3532     _previous_version_count--;
3533     return;
3534   }
3535 
3536   if (emcp_method_count != 0) {
3537     // At least one method is still running, check for EMCP methods
3538     for (int i = 0; i < old_methods->length(); i++) {
3539       Method* old_method = old_methods->at(i);
3540       if (!old_method->is_obsolete() && old_method->on_stack()) {
3541         // if EMCP method (not obsolete) is on the stack, mark as EMCP so that
3542         // we can add breakpoints for it.
3543 
3544         // We set the method->on_stack bit during safepoints for class redefinition
3545         // and use this bit to set the is_running_emcp bit.
3546         // After the safepoint, the on_stack bit is cleared and the running emcp
3547         // method may exit.   If so, we would set a breakpoint in a method that
3548         // is never reached, but this won't be noticeable to the programmer.
3549         old_method->set_running_emcp(true);
3550         RC_TRACE(0x00000400, ("add: EMCP method %s is on_stack " INTPTR_FORMAT,
3551                               old_method->name_and_sig_as_C_string(), old_method));
3552       } else if (!old_method->is_obsolete()) {
3553         RC_TRACE(0x00000400, ("add: EMCP method %s is NOT on_stack " INTPTR_FORMAT,
3554                               old_method->name_and_sig_as_C_string(), old_method));
3555       }
3556     }
3557   }
3558 
3559   // Add previous version if any methods are still running.
3560   RC_TRACE(0x00000400, ("add: scratch class added; one of its methods is on_stack"));
3561   assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");
3562   scratch_class->link_previous_versions(previous_versions());
3563   link_previous_versions(scratch_class());
3564   // Update count for class unloading.
3565   _previous_version_count++;
3566 } // end add_previous_version()
3567 
3568 
3569 Method* InstanceKlass::method_with_idnum(int idnum) {
3570   Method* m = NULL;
3571   if (idnum < methods()->length()) {
3572     m = methods()->at(idnum);
3573   }
3574   if (m == NULL || m->method_idnum() != idnum) {
3575     for (int index = 0; index < methods()->length(); ++index) {
3576       m = methods()->at(index);
3577       if (m->method_idnum() == idnum) {
3578         return m;
3579       }
3580     }
3581     // None found, return null for the caller to handle.
3582     return NULL;
3583   }
3584   return m;
3585 }
3586 
3587 
3588 Method* InstanceKlass::method_with_orig_idnum(int idnum) {
3589   if (idnum >= methods()->length()) {
3590     return NULL;
3591   }
3592   Method* m = methods()->at(idnum);
3593   if (m != NULL && m->orig_method_idnum() == idnum) {
3594     return m;
3595   }
3596   // Obsolete method idnum does not match the original idnum
3597   for (int index = 0; index < methods()->length(); ++index) {
3598     m = methods()->at(index);
3599     if (m->orig_method_idnum() == idnum) {
3600       return m;
3601     }
3602   }
3603   // None found, return null for the caller to handle.
3604   return NULL;
3605 }
3606 
3607 
3608 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {
3609   InstanceKlass* holder = get_klass_version(version);
3610   if (holder == NULL) {
3611     return NULL; // The version of klass is gone, no method is found
3612   }
3613   Method* method = holder->method_with_orig_idnum(idnum);
3614   return method;
3615 }
3616 
3617 
3618 jint InstanceKlass::get_cached_class_file_len() {
3619   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
3620 }
3621 
3622 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
3623   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
3624 }
--- EOF ---